Data Structures & AlgorithmsVery hardProduct company OA

Dijkstra with a binary heap and lazy deletion (no decrease-key; outdated entries are skipped when popped). What is printed (dist to E, total pops, stale pops)?

Dijkstra with a binary heap and lazy deletion (no decrease-key; outdated entries are skipped when popped). What is printed (dist to E, total pops, stale pops)?
import heapq
g = {"A": [("B", 7), ("C", 2), ("D", 9)], "B": [("E", 1)], "C": [("B", 3), ("D", 5)], "D": [("E", 1)], "E": []}
dist = {"A": 0}; h = [(0, "A")]; pops = stale = 0
while h:
    d, u = heapq.heappop(h); pops += 1
    if d > dist[u]: stale += 1; continue
    for v, w in g[u]:
        if d + w < dist.get(v, 10**9):
            dist[v] = d + w; heapq.heappush(h, (d + w, v))
print(dist["E"], pops, stale)
  1. A. 6 5 0
  2. B. 6 7 2
  3. C. 8 7 2
  4. D. 6 9 4

Correct answer: B. 6 7 2

From A: push B 7, C 2, D 9. Pop C (2): improves B to 5 and D to 7 – the old (7, B) and (9, D) entries stay in the heap. Pop B (5) → E becomes 6. Then the heap pops E (6), the outdated (7, B) – skipped, D (7) – no improvement to E – and the outdated (9, D) – skipped. 7 pops in total (A, C, B, E, B, D, D), 2 of them stale. Lazy deletion allows up to E heap entries, so it is O(E log E) = O(E log V).

More Trees, Graphs, Recursion and Dynamic Programming questions

Exams that ask this topic