Data Structures & AlgorithmsModerateProduct Company SDE · Amazon/Microsoft-style OA

Problem: BFS shortest path on a grid (Python):

Problem: BFS shortest path on a grid (Python):
q = deque([start]); dist = {start: 0}
while q:
    u = q.popleft()
    for v in neighbours(u):
        if v not in dist:
            q.append(v)          # line 6
    dist[u] = dist.get(u, 0)     # line 7
Distances come out as 0 for every cell. Which change fixes it?
  1. A. Set dist[v] = dist[u] + 1 when v is first discovered (before or at line 6) and delete line 7
  2. B. Use a stack instead of a deque
  3. C. Move line 7 above the for loop
  4. D. Mark v visited when it is popped instead of when pushed

Correct answer: A. Set dist[v] = dist[u] + 1 when v is first discovered (before or at line 6) and delete line 7

Distances must be assigned when a node is discovered, from its parent's distance. As written, nothing ever stores a positive distance (and since v is never added to dist, nodes can be enqueued many times). Marking on pop makes duplicates worse; a stack turns BFS into DFS, which is not shortest-path.

More Coding Interview Problems questions

Exams that ask this topic