Dijkstra's algorithm
medium 22 minDijkstra's algorithm finds the shortest distance from one source to every node of a graph whose edge weights are non-negative.
See it run
Watch the min-heap settle the closest node, relax its edges and skip stale entries until every shortest distance is final.
Operations
Shortest paths from A
The old app's simple graph: six nodes, nine undirected weighted edges. Find the shortest distance from A to every node.
Step 1 of 11
Initialise
heap (min first)
(0,A)
settled
empty
dist(A) = 0, every other node is \infty: not reached yet. The heap holds one entry, (0, A). Each node's number under it is its current best distance.
Step 1: Initialise
import heapqdef dijkstra(graph, src): dist = {v: float("inf") for v in graph} prev = {v: None for v in graph} dist[src] = 0 pq = [(0, src)] # (distance, node) while pq: d, u = heapq.heappop(pq) # closest entry if d > dist[u]: continue # stale: u already settled cheaper for v, w in graph[u]: nd = d + w if nd < dist[v]: # relax u -> v dist[v] = nd prev[v] = u heapq.heappush(pq, (nd, v)) # push again, no decrease-key return dist, prevgraph = { "A": [("B", 4), ("C", 2)], "B": [("A", 4), ("C", 1), ("D", 5)], "C": [("A", 2), ("B", 1), ("D", 8), ("E", 10)], "D": [("B", 5), ("C", 8), ("E", 2), ("F", 6)], "E": [("C", 10), ("D", 2), ("F", 3)], "F": [("D", 6), ("E", 3)],}dist, prev = dijkstra(graph, "A")print(dist) # {'A': 0, 'B': 3, 'C': 2, 'D': 8, 'E': 10, 'F': 13}- Time
- O((V + E) log V)
- Space
- O(V + E)
- pushes / pops here
- 9 / 10
- array scan instead
- O(V²)
Settle on pop, never on push: a node's distance is final only when it is the heap's minimum.
In the real world
The same dijkstra's algorithm doing real jobs. Pick one and step through it.
A navigation app finds the fastest drive. Weights are hours; it stops as soon as the destination is settled.
Step 1 of 7
Pick a route
heap (min first)
(0,NYC)
settled
empty
From NYC to MIA. Eight cities, twelve highways. The app runs Dijkstra from NYC and may stop early: once MIA is popped, its time is final.
Step 1: Pick a route
import heapqdef fastest_route(graph, src, dst): dist, prev = {src: 0}, {src: None} pq = [(0, src)] while pq: d, u = heapq.heappop(pq) if d > dist[u]: continue if u == dst: break # destination settled: stop early for v, w in graph[u]: if d + w < dist.get(v, float("inf")): dist[v], prev[v] = d + w, u heapq.heappush(pq, (d + w, v)) else: return None, [] # heap ran dry: unreachable path, node = [], dst while node is not None: path.append(node) node = prev[node] return dist[dst], path[::-1]roads = [("NYC", "BOS", 4), ("NYC", "DC", 4), ("NYC", "CHI", 12), ("BOS", "CHI", 14), ("DC", "CHI", 11), ("DC", "ATL", 10), ("CHI", "DAL", 13), ("CHI", "DEN", 15), ("ATL", "DAL", 12), ("ATL", "MIA", 10), ("DAL", "DEN", 11), ("DAL", "MIA", 18)]graph = {}for a, b, h in roads: graph.setdefault(a, []).append((b, h)) graph.setdefault(b, []).append((a, h))print(fastest_route(graph, "NYC", "MIA")) # (24, ['NYC', 'DC', 'ATL', 'MIA'])Common mistakes
The bugs interviewers watch for, with the fix beside each.
Running Dijkstra with negative weights
criticalA popped node is final only because later routes can only add cost. One negative edge breaks that, and the answer is silently wrong. Use Bellman-Ford (or SPFA) instead, which also detects negative cycles.
Wrong# weights may be negative (refunds, energy gains)dist = dijkstra(graph, src)Rightif any(w < 0 for u in graph for _, w in graph[u]): dist = bellman_ford(graph, src) # O(V * E), handles negativeselse: dist = dijkstra(graph, src)Settling a node when it is pushed
criticalMarking visited on push is right for BFS, where the first discovery is the shortest. In Dijkstra the first discovery is only a guess: B was first reached at 4 and later improved to 3. Settle on pop.
Wrongfor v, w in graph[u]: if v not in seen: seen.add(v) # too early: 4 might become 3 dist[v] = d + w heapq.heappush(pq, (dist[v], v))Rightfor v, w in graph[u]: if d + w < dist[v]: # improve as often as needed dist[v] = d + w heapq.heappush(pq, (dist[v], v))# a node is final only when it is popped and not staleNot skipping stale entries
majorWith lazy deletion the heap holds old (distance, node) pairs. Processing them again re-relaxes every edge of that node: still correct with non-negative weights, but it wastes work and breaks any per-node counting such as 'number of nodes reached'.
Wrongd, u = heapq.heappop(pq)for v, w in graph[u]: # runs again for every stale copy ...Rightd, u = heapq.heappop(pq)if d > dist[u]: continue # stale: a shorter entry already wonfor v, w in graph[u]: ...Pushing (node, distance) instead of (distance, node)
majorheapq compares tuples from the first field. With the node first, the heap pops in alphabetical order of names, not by distance, and the greedy choice is gone.
Wrongheapq.heappush(pq, (v, nd)) # orders by node labelRightheapq.heappush(pq, (nd, v)) # orders by distanceStopping when the target is pushed
majorA pushed distance can still improve. In the simple graph F was first pushed at 14 and later improved to 13. Stop only when the target is popped (and not stale).
Wrongif nd < dist[v]: dist[v] = nd if v == target: return nd # 14, but the answer is 13Rightd, u = heapq.heappop(pq)if d > dist[u]: continueif u == target: return d # final: 13Adding undirected edges in one direction only
minorA two-way road must appear in both adjacency lists. Missing the reverse direction makes some nodes unreachable or their routes longer.
Wrongfor a, b, w in roads: graph[a].append((b, w))Rightfor a, b, w in roads: graph[a].append((b, w)) graph[b].append((a, w)) # two-way
Interview tips
How to explain it
- Dijkstra is BFS with the FIFO queue swapped for a min-heap keyed by distance: closest first instead of oldest first.
- Pop the closest node, call it final, relax its edges: if dist[u] + w < dist[v], lower dist[v], set prev[v] = u and push.
- Lazy deletion: push a new entry on every improvement and skip entries with d > dist[u] when they surface.
- O((V + E) log V) time with a binary heap, O(V + E) space; non-negative weights only.
Spot it in the wild
- Shortest, cheapest, fastest or least risky route with non-negative costs.
- Network delay, signal latency, minimum effort on a height grid, maximum probability path.
- Grids where cells have different costs: BFS no longer works, Dijkstra does.
Interview traps
- Negative edges: name Bellman-Ford straight away.
- Settle on pop, not on push, and stop early only when the target is popped.
- A limit on stops (K stops) changes the state to (node, stops); plain Dijkstra on node alone is wrong.
Variants to name
- Unweighted: BFS. Weights only 0 or 1: 0-1 BFS with a deque.
- One target with a good estimate: A*. All pairs on a small graph: Floyd-Warshall.
- Dense graph: the O(V²) array version beats the heap.