Debugging challengeAdvanced
Dijkstra returns wrong distances
Scenario
A routing service computes single-source shortest paths with the implementation below. Unit tests pass, but on the production graph dist[3] comes back as 4 although a path of cost 2 exists: 0 → 2 → 1 → 3 with weights 5, -4, 1. Edges are given as (u, v, w). The code itself is a textbook Dijkstra. Find the problem.
Broken
1import heapq2 3def dijkstra(n, edges, src):4 adj = [[] for _ in range(n)]5 for u, v, w in edges:6 adj[u].append((v, w))7 8 dist = [float('inf')] * n9 dist[src] = 010 pq = [(0, src)]11 done = [False] * n12 13 while pq:14 d, u = heapq.heappop(pq)15 if done[u]:16 continue17 done[u] = True18 for v, w in adj[u]:19 if d + w < dist[v]:20 dist[v] = d + w21 heapq.heappush(pq, (dist[v], v))22 return dist23 24# production input25edges = [(0, 1, 3), (0, 2, 5), (2, 1, -4), (1, 3, 1)]26print(dijkstra(4, edges, 0)) # [0, 3, 5, 4] — expected dist[3] == 2The corrected version appears here once you have revealed everything below.
Your task
- Confirm the code is a correct Dijkstra. Then look at the *input*: what property of the graph is violated?
- Trace the algorithm on the given edges and show exactly at which step the wrong answer becomes irreversible.
- Explain why the greedy "settle the closest vertex" step depends on non-negative weights.
- Propose a fix. There is more than one reasonable answer — discuss the trade-offs.
- State the complexity of the fixed approach.
DebuggingSystematic ReasoningPattern Recognition
Work it out
Write your analysis before revealing anything. The self-check below compares it against what a strong answer contains.
Reveal
Progressive — each section builds on the previous one.
The bug
Why it happens
The fix
Edge cases
Complexity
What this tests
Self-check
Tick what your analysis covered. Be honest — this feeds your readiness profile.