Data Structures & AlgorithmsVery hardProduct company OA

Problem: Two versions of Dijkstra. The second marks a vertex as finished the moment it is first PUSHED and never updates it again.

Problem: Two versions of Dijkstra. The second marks a vertex as finished the moment it is first PUSHED and never updates it again.
import heapq
def dijkstra(g, s, mark_on_push):
    dist = {s: 0}; done = set(); h = [(0, s)]
    if mark_on_push: done.add(s)
    while h:
        d, u = heapq.heappop(h)
        if not mark_on_push:
            if u in done: continue
            done.add(u)
        for v, w in g[u]:
            if mark_on_push:
                if v in done: continue
                done.add(v); dist[v] = d + w; heapq.heappush(h, (d + w, v))
            elif d + w < dist.get(v, 10**9):
                dist[v] = d + w; heapq.heappush(h, (d + w, v))
    return dist
g = {"S": [("A", 10), ("B", 1)], "B": [("C", 1)], "C": [("A", 1), ("T", 20)], "A": [("T", 2)], "T": []}
print(dijkstra(g, "S", False)["T"], dijkstra(g, "S", True)["T"])
What is printed?
  1. A. 5 5
  2. B. 22 5
  3. C. 5 22
  4. D. 13 22

Correct answer: C. 5 22

Marking on push freezes A at 10 (direct edge S → A) before the cheaper route S → B → C → A of cost 3 is found, and C's edge to A is ignored. C is popped before A, so T is first pushed – and frozen – with 2 + 20 = 22; the later route through A is ignored too. The correct version marks on POP, so A's distance can still drop: S → B → C → A → T = 1 + 1 + 1 + 2 = 5. Finalise a vertex only when it leaves the heap with its minimum key.

More Coding Interview Problems questions

Exams that ask this topic