Data Structures & AlgorithmsVery hardGoogle · Flipkart interview

Problem: Dijkstra with a lazy binary heap: outdated heap entries are skipped when popped. Report the distance to node 4 and how many stale entries were skipped.

Problem: Dijkstra with a lazy binary heap: outdated heap entries are skipped when popped. Report the distance to node 4 and how many stale entries were skipped.
import heapq
def run(n, edges, s):
    g = [[] for _ in range(n)]
    for u, v, w in edges: g[u].append((v, w))
    dist = [float('inf')] * n; dist[s] = 0
    h, stale = [(0, s)], 0
    while h:
        d, u = heapq.heappop(h)
        if d > dist[u]:
            stale += 1; continue
        for v, w in g[u]:
            if d + w < dist[v]:
                dist[v] = d + w; heapq.heappush(h, (dist[v], v))
    return dist[4], stale
print(*run(5, [(0,1,4),(0,2,1),(2,1,2),(1,3,1),(2,3,5),(3,4,3)], 0))
What is printed?
  1. A. 7 0
  2. B. 8 2
  3. C. 7 1
  4. D. 7 2

Correct answer: D. 7 2

Popping 0 pushes (4,1) and (1,2); popping 2 improves 1 to 3 and pushes (6,3); popping 1 improves 3 to 4. The old entries (4,1) and (6,3) are both popped later and skipped, so stale = 2, and dist[4] = 4 + 3 = 7 via 0→2→1→3→4.

More Coding Interview Problems questions

Exams that ask this topic