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)- A. 6 5 0
- B. 6 7 2
- C. 8 7 2
- 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).
Practise more Trees, Graphs, Recursion and Dynamic Programming questionsTrees, Graphs, Recursion and Dynamic Programming: notes and key points
More Trees, Graphs, Recursion and Dynamic Programming questions
- AVL insertions (rotations labelled by imbalance case). What is printed (preorder, rotation cases in order, height in edges)? python class…
- B-tree with minimum degree t = 2 (a 2-3-4 tree, at most 3 keys per node) using the single-pass insertion that splits every FULL node on…
- Building a min-heap from [9, 8, 7, 6, 5, 4, 3]: (a) seven sift-up insertions, (b) bottom-up heapify. What is printed (heaps and swap…
- Exact count of the innermost statement for n = 30 (j advances by i, k advances by j). What is printed? python c = 0 n = 30 for i in…
- A memoised recursion f(n) = f(n//2) + f(n//3) + f(n//6) is evaluated for n = 10¹². How many distinct calls (cache misses) are made? python…
- Patience-sorting tails array for the longest STRICTLY increasing subsequence, and the length for the non-decreasing variant. What is…