Lesson 6 of 6
Weighted shortest paths
When edges have different costs, the route with the fewest edges is not always the cheapest. Dijkstra's algorithm settles the closest node first, keeps a heap of (distance, node) pairs, and finds every shortest distance in O((V + E) log V).
Show with a small graph why breadth-first search records wrong distances once edges have weights
Run Dijkstra's algorithm by hand, pop by pop, settling nodes, relaxing edges and skipping stale pairs
Write Dijkstra with heapq and a dist dict, and say its walk, notebook, promise and cost
Rebuild the shortest route itself with a dict of previous nodes
Explain why every weight must be 0 or more, and what to use when some are negative
Adapt Dijkstra to a route cost that is not a sum, such as the largest single step
Four servers pass messages along one-way links. Each link has a delay in milliseconds:
| link | delay |
|---|---|
| A to B | 4 |
| A to C | 1 |
| C to B | 2 |
| B to D | 1 |
| C to D | 6 |
A message leaves A at time 0. When does it first reach each server? A has a direct link to B, so 4 looks like the answer for B. But the route A, C, B takes 1 + 2 = 3 milliseconds, which is sooner. The route with the fewest links is not always the fastest.
This is a weighted graph: a set of nodes (the servers) joined by edges (the links), where each edge carries a number called its weight (the delay). These edges are directed: a link from A to B gives no way back from B to A. A route's distance is the sum of the weights along it. A shortest path from a starting node, the source, to another node is a route between them with the smallest distance. This lesson finds every shortest distance from the source with Dijkstra's algorithm, named after Edsger Dijkstra.
Fewest edges is not cheapest
Does breadth-first search still work? A reminder of how it walks: it takes nodes from a queue in the order it found them, and records each node's distance the first time it reaches it. When every edge counts as 1, the first time is the shortest.
The graph is stored as an adjacency list: a dict from each node to a list of (neighbor, weight) pairs, one per link leaving it. (A two-way link would sit in both nodes' lists.) The code below is the distances function you wrote in the breadth-first search lesson, renamed bfs_times. Its dist dict also does the visited set's job: a node is in dist once it has joined the queue. There is one change: a node's distance is the distance of the node it came from plus the link's delay, instead of plus 1. Before you step through, guess what it records for B and for D.
from collections import dequedef bfs_times(graph, source):dist = {source: 0}queue = deque([source])while queue:node = queue.popleft()for nbr, w in graph[node]:if nbr not in dist:dist[nbr] = dist[node] + wqueue.append(nbr)return distgraph = {"A": [("B", 4), ("C", 1)],"B": [("D", 1)],"C": [("B", 2), ("D", 6)],"D": [],}print(bfs_times(graph, "A"))
(nothing printed yet)The first route breadth-first search finds is the one with the fewest edges, and it never looks again. B gets 4 because the direct link is one edge, though the two-edge route through C costs 3. D inherits the mistake: 4 + 1 = 5 instead of 3 + 1 = 4. Weights broke the promise of breadth-first search: the first distance a node gets is no longer its shortest.
This is the breadth-first search from the trace above, run on a new graph. Type exactly what it prints.
from collections import deque
def bfs_times(graph, source):
dist = {source: 0}
queue = deque([source])
while queue:
node = queue.popleft()
for nbr, w in graph[node]:
if nbr not in dist:
dist[nbr] = dist[node] + w
queue.append(nbr)
return dist
graph = {
"S": [("A", 1), ("B", 7)],
"A": [("C", 1)],
"B": [("T", 1)],
"C": [("B", 1)],
"T": [],
}
times = bfs_times(graph, "S")
print(times["B"], times["T"])
Settle the closest node first
So which distances can we trust? Go back to the moment A's two links have been checked: B is known at 4 and C at 1, and C's 1 is already final. Any other route to C would have to leave A some other way, and the only other way out of A is the link to B, which already costs 4. Delays are never negative, so whatever follows can only add to that 4.
That gives the whole algorithm, with two words to learn:
- Settle a node: declare its distance final. Call a node waiting when it has been reached but not settled. Always settle the waiting node with the smallest known distance.
- Relax an edge out of a settled node: if the settled node's distance plus the edge's weight beats the neighbor's best known distance, lower the neighbor's distance to that sum.
Why the smallest waiting distance is safe to settle: any route to that node has to step off the settled nodes somewhere. The settled node it steps from has already relaxed that edge, so the route reaches the next node at no less than that node's known distance, which is at least the smallest. Every weight after that adds 0 or more. Settle, relax, repeat, until no node is waiting.
The widget runs this on the four servers. It keeps the waiting (distance, node) pairs in a heap, the structure from How a heap works that always hands back its smallest item. Adding a pair is a push, and taking the smallest pair out is a pop. When a node's distance drops, a new pair is pushed and the old pair stays inside. The old pair is now stale: its distance is bigger than the node's best, so it is skipped when it comes out.
On screen: the graph with each link's delay, a table with each node's best distance so far and the node it came from, and the heap's pairs, smallest first. After the start, each step is one pop, until the heap is empty. Waiting nodes have an amber ring, and settled nodes turn lime. Before you press Next, guess which node is settled second.
Recap. Each step pops the smallest pair. A fresh pair settles its node and relaxes its edges; a stale pair is skipped. A node can be pushed more than once, as B and D were, but only its first pair out counts. The from column spells out each route backwards: D came from B, B from C, C from A.
Try a run on paper before the code.
Run Dijkstra by hand from S on these one-way links. Keep two things on paper: the best distance for each node, and the heap as a list of (distance, node) pairs, smallest first. Check each node's links in the order listed, and write one line per pop.
| link | weight |
|---|---|
| S to A | 3 |
| S to B | 1 |
| B to A | 1 |
| A to C | 2 |
| B to C | 6 |
| C to D | 1 |
What is the shortest distance from S to D?
Work it on real paper: writing each step is the point. Then check your final answer here and compare your working with the walk-through.
Type a number: 12, -1, 0.5 and 3/4 all work. Enter checks.
A heap picks the closest
Each step needs the smallest distance among the waiting nodes, and a heap hands that over in O(log n). In Python, the heapq module does the work: it keeps the smallest item of a list at index 0, heapq.heappush adds an item and heapq.heappop removes and returns the smallest, each in O(log n) for n items. Tuples compare item by item: the first items decide, and only a tie moves on to the second. So a heap of (distance, node) pairs gives back the smallest distance first, and on a tie the node name decides.
Stale pairs stay in the heap. When B drops from 4 to 3, the pair (4, B) is still inside. heapq cannot remove an item from the middle cheaply, so we leave it there. When it comes out, its 4 is bigger than the 3 recorded in dist, so we skip it. Here is the code on the same four servers. Before you step through, guess the order the pairs come out.
import heapqimport mathdef dijkstra(graph, source):dist = {node: math.inf for node in graph}dist[source] = 0heap = [(0, source)]while heap:d, node = heapq.heappop(heap)if d > dist[node]:continuefor nbr, w in graph[node]:if d + w < dist[nbr]:dist[nbr] = d + wheapq.heappush(heap, (d + w, nbr))return distgraph = {"A": [("B", 4), ("C", 1)],"B": [("D", 1)],"C": [("B", 2), ("D", 6)],"D": [],}print(dijkstra(graph, "A"))
(nothing printed yet)Here is the algorithm in the four questions of this course. V is the number of nodes and E the number of edges.
Check the heap order on a smaller graph.
This is the loop from the trace, with a print on every pop. Type exactly what it prints.
import heapq
import math
graph = {
"A": [("B", 5), ("C", 2)],
"B": [],
"C": [("B", 1)],
}
dist = {"A": 0, "B": math.inf, "C": math.inf}
heap = [(0, "A")]
while heap:
d, node = heapq.heappop(heap)
if d > dist[node]:
print("skip", d, node)
continue
print("settle", d, node)
for nbr, w in graph[node]:
if d + w < dist[nbr]:
dist[nbr] = d + w
heapq.heappush(heap, (d + w, nbr))
Now put the loop together yourself.
Put the lines in order to build dijkstra(graph, source), which returns a dict of the shortest distance from source to every node. graph maps every node to a list of (neighbor, weight) pairs, and heapq and math are already imported. Skip a stale pair right after it is popped, before relaxing anything. Indentation is part of each line. Three lines do not belong.
Add lines from the list below, in order.
dist[source] = 0heap = [(dist[source], source)]for nbr, w in graph[node]:return distif d + w < dist[nbr]:continueif w < dist[nbr]:dist = {node: math.inf for node in graph}heapq.heappush(heap, (dist[nbr], nbr))dist[nbr] = d + wnode = queue.popleft()if d > dist[node]:if d >= dist[node]:d, node = heapq.heappop(heap)def dijkstra(graph, source):while heap:
What it costs
How much work does the loop do? Count it in the trace on the four servers. The four servers have E = 5 links, and 6 pairs entered the heap, counting the start pair. All 6 came out. Six is E + 1, and no run can push more:
- A node is settled once. Its first pair out carries its final distance, and every later pair for it is stale.
- So each edge is relaxed once, when its start node is settled, and each relax pushes at most one pair. With the start pair, that is at most E + 1 pushes, and each pair is popped once.
- Each push or pop costs O(log of the heap's size), and the heap never holds more than E + 1 pairs. A graph with no repeated edges has at most V2 edges, so log E is at most 2 log V, and each push or pop is O(log V).
- Setting up
disttouches each of the V nodes once.
Together: O(V) for the setup plus O(E log V) for the heap, which fits inside O((V + E) log V) time, the bound usually quoted. The space is the adjacency lists, dist and the heap: O(V + E). Without a heap, finding the smallest waiting distance by scanning every node costs O(V) per settle, O(V2) in all. That wins only on dense graphs, where E is close to V2.
Only an improvement pushes. Count the pushes on a graph where one relax fails.
Run Dijkstra from A on these one-way links, checking each node's links in the order listed:
| link | weight |
|---|---|
| A to B | 1 |
| A to C | 4 |
| B to C | 2 |
| C to B | 1 |
How many pairs enter the heap in all, counting the start pair (0, A)?
Type a number: 12, -1, 0.5 and 3/4 all work. Enter checks.
Reading answers out of the notebook
What do you do with dist once the walk ends? Interview questions rarely want the whole dict: they want an answer read out of it, such as the route itself or the latest arrival.
A shortest route is one more dict away. Whenever a relax lowers dist[nbr], the node you came from is the best way into nbr so far. Record it, and at the end follow those records back from the target.
Write shortest_route(graph, source, target), which returns the nodes of the fastest route from source to target as a list, source first. Return [] if no route exists. graph maps every node to a list of (neighbor, weight) pairs, every weight is 0 or more, and in every test the fastest route is unique.
Run Dijkstra and keep one more dict, prev: whenever a relax lowers dist[nbr], set prev[nbr] = node. When the walk ends, prev leads from target back to source. Then press Watch it run to see prev fill in.
raise NotImplementedError, then press Run tests. Each check says what it expects.The first full problem asks for the latest arrival. It is the four-server story at any size. Its walk is the dijkstra loop above; only the setup and the answer change. The links arrive as [u, v, w] triples, so build the adjacency lists first with defaultdict(list). The servers are labeled 1 to n, so the solution keeps the times in a list called arrival with n + 1 slots and leaves slot 0 unused. And the question asks when the last server hears: that is the largest of the shortest times, or -1 if some server is still at infinity.
The answer reads the notebook once more after the walk: the largest value in arrival[1:], because every server hears at its own fastest time and the last to hear sets the answer. The slice leaves out slot 0, which stays at infinity. The brute force in the solution, Bellman-Ford, relaxes every link in n − 1 rounds (the next section comes back to it). On the test's chain of 12,000 servers that is about 144 million link checks, where Dijkstra settles each server once.
Negative weights break the promise
What happens when a weight is negative? Start with a shortcut. When you need the distance to one target node only, return the moment the target is settled: popped, and not stale. The promise says its distance is final, so nothing later can change it. The second problem in this lesson uses this shortcut. But the promise leaned on one fact: weights are never negative. Here is the shortcut on a graph with one negative link. The real shortest route to B is A, C, B: 3 + (−2) = 1. Before you step through, guess what the code returns.
import heapqimport mathdef shortest_to(graph, source, target):dist = {node: math.inf for node in graph}dist[source] = 0heap = [(0, source)]while heap:d, node = heapq.heappop(heap)if d > dist[node]:continueif node == target:return dfor nbr, w in graph[node]:if d + w < dist[nbr]:dist[nbr] = d + wheapq.heappush(heap, (d + w, nbr))return math.infgraph = {"A": [("B", 2), ("C", 3)],"B": [],"C": [("B", -2)],}print(shortest_to(graph, "A", "B"))
(nothing printed yet)A negative weight lets a longer route become cheaper after the node was settled. The argument "every weight after that adds 0 or more" fails, because a later edge can subtract. So Dijkstra needs every weight to be 0 or more. Zero is fine: it adds nothing, so it never lowers a distance.
Without the early return, the loop would go on: pop C, lower B to 1, push (1, "B"), and settle B a second time. It returns the right 1 here, but a node settled twice means a popped distance was not final, and the cost argument, which counted one settle per node, no longer holds either.
Your interviewer changes network delay time: some delays can now be negative, though no loop of links adds up to a negative total. What do you say?
Choose one answer, then check.
When a route's cost is not a sum
Does Dijkstra only work for sums? Dijkstra never needed the sum itself. It needs one property: making a route longer never makes it cheaper. Here is a route cost that is not a sum. A robot crosses a field of cells, each with a height. A move goes to the next cell, its step is the height difference, up or down, and the effort of a route is its largest step. abs(x) drops the sign, so the move from 5 down to 4 has a step of abs(4 - 5), which is 1. The effort of one route is a running maximum, the loop from Walking a list. Guess the effort of this route before you step through.
route = [2, 5, 4, 8, 7]effort = 0for i in range(1, len(route)):step = abs(route[i] - route[i - 1])effort = max(effort, step)print(effort)
(nothing printed yet)A running maximum never goes down, so the effort of a route never drops as it grows. That is the property Dijkstra needs. Popping the smallest effort is final for the same reason as before: any route to that cell steps off the settled cells somewhere, onto a waiting cell at an effort no smaller than the smallest, and later steps cannot lower a maximum.
Dijkstra is right when the pair it pops is final. Each option says how a route's cost changes when the route takes one more edge of weight w. For which ones does popping the smallest cost stay final? Pick every one that works.
Choose every option that applies, then check.
The second problem puts this on a grid. Each cell is a node, and its neighbors are the cells up, down, left and right that are inside the grid. For the cell at row r, column c, call a neighbor's row and column nr and nc. The step of that move is abs(heights[nr][nc] - heights[r][c]), and one more move turns the effort from so_far into max(so_far, step). The notebook becomes a grid effort[r][c], infinity at first, and the heap holds (effort, row, col) triples. Only the bottom-right cell matters, so return the moment it is settled.
Compared with network delay time, the new cost lives in one expression: max(so_far, step) where the delays used now + delay. The neighbors come from the grid instead of stored lists, and the rest is the same loop: pop, skip stale, relax, push. The solution's follow-ups show two other ways to solve it, binary search on the effort limit and union-find. Both are worth knowing when an interviewer asks "why this approach?".
In the Practice bank, cheapest flights within k stops (LeetCode 787) adds a limit on how many flights a trip may use. Settling each city once no longer works there: a pricier arrival that used fewer flights may be the only one that can still finish the trip, so each heap entry also carries the flights used so far.
Last, say it out loud.
Explain to an interviewer, before typing, how you would solve network delay time: the walk, the notebook, the promise and the cost. Then answer the follow-up: why a heap and not the queue from breadth-first search?
Saved in this browser as you type.