Data Structures & AlgorithmsHardInfosys SP/DSE · Product Company SDE

Problem: Find the inefficiency: two BFS versions on an R × C open grid. One marks a cell visited when it is pushed, the other only when it is popped. Count total pushes.

Problem: Find the inefficiency: two BFS versions on an R × C open grid. One marks a cell visited when it is pushed, the other only when it is popped. Count total pushes.
from collections import deque
D = ((1, 0), (0, 1), (-1, 0), (0, -1))
def bfs_early(R, C):
    q = deque([(0, 0)]); seen = {(0, 0)}; pushes = 1
    while q:
        i, j = q.popleft()
        for di, dj in D:
            ni, nj = i + di, j + dj
            if 0 <= ni < R and 0 <= nj < C and (ni, nj) not in seen:
                seen.add((ni, nj)); q.append((ni, nj)); pushes += 1
    return pushes
def bfs_late(R, C):
    q = deque([(0, 0)]); seen = set(); pushes = 1
    while q:
        cell = q.popleft()
        if cell in seen: continue
        seen.add(cell); i, j = cell
        for di, dj in D:
            ni, nj = i + di, j + dj
            if 0 <= ni < R and 0 <= nj < C and (ni, nj) not in seen:
                q.append((ni, nj)); pushes += 1
    return pushes
print(bfs_early(3, 3), bfs_late(3, 3), bfs_early(10, 10), bfs_late(10, 10))
What is printed?
  1. A. 9 13 100 400
  2. B. 13 9 181 100
  3. C. 9 9 100 100
  4. D. 9 13 100 181

Correct answer: D. 9 13 100 181

Marking on push guarantees each cell enters the queue exactly once (R·C pushes). Marking on pop lets a cell be pushed by several neighbours before it is processed – 13 pushes for 9 cells, 181 for 100 – still correct thanks to the 'if cell in seen: continue' guard, but the queue can grow to O(E) and, without that guard, cells would be expanded repeatedly. Both are O(R·C) here, but the early-mark version uses less memory and time.

More Coding Interview Problems questions

Exams that ask this topic