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 7Distances come out as 0 for every cell. Which change fixes it?- A. Set dist[v] = dist[u] + 1 when v is first discovered (before or at line 6) and delete line 7
- B. Use a stack instead of a deque
- C. Move line 7 above the for loop
- 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
- Problem: Detect whether an undirected graph has a cycle with DFS: python def dfs(u): seen.add(u) for v in adj[u]: if v in seen: return…
- Problem: Climbing-stairs memoisation in Python: python def ways(n, memo={}): if n <= 1: return 1 if n in memo: return memo[n] memo[n] =…
- Problem: Reverse a singly linked list (C++): cpp Node prev = nullptr; while (head) { head->next = prev; // line 3 prev = head; head =…
- Problem: A sliding-window solution for 'longest substring with at most k distinct characters' keeps a frequency map and shrinks while…
- Problem: Merge sort's merge step in Java uses if (a[i] < b[j]) take a[i]; else take b[j];. What property is lost compared with <=?
- Problem: The 'two-sum on a sorted array' code below has a subtle edge-case behaviour. What does it print? python def twosumsorted(a, t)…