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 heapq
2
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')] * n
9 dist[src] = 0
10 pq = [(0, src)]
11 done = [False] * n
12
13 while pq:
14 d, u = heapq.heappop(pq)
15 if done[u]:
16 continue
17 done[u] = True
18 for v, w in adj[u]:
19 if d + w < dist[v]:
20 dist[v] = d + w
21 heapq.heappush(pq, (dist[v], v))
22 return dist
23
24# production input
25edges = [(0, 1, 3), (0, 2, 5), (2, 1, -4), (1, 3, 1)]
26print(dijkstra(4, edges, 0)) # [0, 3, 5, 4] — expected dist[3] == 2

The corrected version appears here once you have revealed everything below.

Your task

  1. Confirm the code is a correct Dijkstra. Then look at the *input*: what property of the graph is violated?
  2. Trace the algorithm on the given edges and show exactly at which step the wrong answer becomes irreversible.
  3. Explain why the greedy "settle the closest vertex" step depends on non-negative weights.
  4. Propose a fix. There is more than one reasonable answer — discuss the trade-offs.
  5. 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.

0/7

Related concepts