Shortest paths and minimum spanning trees. The biggest share of marks, and it reuses heaps and greedy thinking.
Open the interactive lessons →Graph Algorithms past questions
Contents
- Graphs: the words and how to store them
- Breadth-first search (BFS): level by level
- Depth-first search (DFS): go deep, then back up
- Shortest paths: the big picture and relaxation
- Dijkstra's algorithm, step by step
- Bellman-Ford and Floyd-Warshall
- Minimum spanning trees: cut and cycle rules, Prim, Kruskal
- Disjoint Set Union (union-find)
- Topological sort and longest paths in a DAG
1. Graphs: the words and how to store them
A graph is dots joined by lines. Store it as a grid of yes/no answers, or as a list of neighbours for each dot.
What vertices and edges are, and the two standard ways to put a graph into a program.
The question this lesson answers. How should a program store a graph, and what does that choice cost?
This is week 4 groundwork. Past questions rarely ask it directly, but every graph algorithm assumes it. Try the questions at the end first; if you get them all, move on.
Who follows whom: you can keep a huge table with a tick for every possible pair, or give each person a short list of the accounts they follow.
A graph $G=(V,E)$ is a set of vertices $V$ (dots) and a set of edges $E$ (links between two dots). In a directed graph the edge $u\to v$ goes one way only. In an undirected graph $u - v$ works both ways. A weighted graph also puts a number (cost) on each edge.
| Word | Meaning |
|---|---|
| neighbour of $u$ | a vertex $v$ with an edge $u\to v$ |
| degree | number of edges at a vertex; directed graphs split it into indegree (coming in) and outdegree (going out) |
| path | a walk along edges that does not repeat a vertex |
| cycle | a route along edges that returns to its start without repeating an edge or any other vertex |
| connected (undirected) | every vertex can reach every other |
Way 1: adjacency matrix. A $V\times V$ grid. Row $u$, column $v$ holds 1 if the edge $u\to v$ exists, else 0. For weights, store the weight and use ∞ for "no edge".
| from \ to | P | Q | R | S |
|---|---|---|---|---|
| P | 0 | 1 | 1 | 0 |
| Q | 0 | 0 | 1 | 0 |
| R | 0 | 0 | 0 | 0 |
| S | 1 | 0 | 0 | 0 |
Read it both ways: the ones in row P are the edges leaving P (outdegree 2); the ones in column R are the edges entering R (indegree 2). For an undirected graph the grid is symmetric.
Way 2: adjacency list. For every vertex, keep only the neighbours that exist.
Both forms, built from one edge list
V = ["P", "Q", "R", "S"]
E = [("P", "Q"), ("P", "R"), ("Q", "R"), ("S", "P")]
index = {v: i for i, v in enumerate(V)}
matrix = [[0] * len(V) for _ in V]
adj = {v: [] for v in V} # every vertex gets a key, even with no edges
for u, v in E:
matrix[index[u]][index[v]] = 1
adj[u].append(v)
# undirected graph: also set matrix[v][u] and do adj[v].append(u)
# adj == {"P": ["Q", "R"], "Q": ["R"], "R": [], "S": ["P"]}
Why the costs differ. The matrix has a box for every possible pair, so one lookup answers "is there an edge?", but finding the neighbours of $u$ means reading all $V$ boxes of its row, mostly zeros. The list stores only real edges, so you read exactly the neighbours, but to test one edge you must search the list.
| Task | Matrix | List |
|---|---|---|
| space | $O(V^2)$ | $O(V+E)$ |
| is there an edge $u\to v$? | $O(1)$ | $O(\text{outdegree of }u)$ |
| list the neighbours of $u$ | $O(V)$ | $O(\text{outdegree of }u)$ |
| visit every edge once | $O(V^2)$ | $O(V+E)$ |
Add up the lengths of all the lists: each directed edge appears once, so the total is $E$. In an undirected graph each edge sits in two lists, so the degrees add to $2E$. This one fact is why searching a whole graph costs $O(V+E)$.
Worked example: Which storage?
Problem.
A road map has $V=10{,}000$ junctions and $E=30{,}000$ one-way roads. Compare the space, and the work to look at the neighbours of every junction once.
Idea.
Compare $V^2$ with $V+E$.
- Matrix: $V^2=10^8$ boxes. List: $V+E=4\times10^4$ entries.
- Looking at all neighbours reads the whole structure, so the same two numbers give the work.
Answer.
The list is about 2500 times smaller and faster here. Choose the matrix only when the graph is dense or you mostly test single edges.
Common mistake.
Assuming $O(V+E)$ is always better: when $E\approx V^2$ the two are the same size.
Matrix: instant edge test. List: only real neighbours.
| Step | Method for any exam question |
|---|---|
| 1 | Note directed or undirected. |
| 2 | Name the storage; it fixes the cost of scanning neighbours. |
| 3 | Sum over all vertices: $V^2$ for a matrix, $V+E$ for lists. |
2. Breadth-first search (BFS): level by level
Visit the start, then all its neighbours, then all their unvisited neighbours, and so on. A queue keeps the order.
The search that visits everything near the start before anything further away.
The question this lesson answers. How do we visit every reachable vertex, closest first?
This is week 4 groundwork. Try the questions at the end first; if you get them all, move on.
News spreading: you tell your friends, then each of them tells their own friends. Nobody is told twice, and people hear it in order of distance from you.
Two things to remember while searching: which vertices have been found (so none is processed twice), and which found vertices still wait to have their neighbours checked. The waiting ones stand in a queue: join at the back, leave from the front.
(1) Mark the start found, level 0, and queue it. (2) Take the front vertex $u$. (3) For each neighbour $v$ not yet found: mark it found, set level($v$) = level($u$) + 1, parent($v$) = $u$, and queue it. (4) Repeat until the queue is empty.
Graph used here (undirected; neighbours are taken in alphabetical order):
A: B, C B: A, D C: A, D, E D: B, C, F E: C, F F: D, E
BFS from A
Mark A as found at level 0 and put it in the queue.
Take A (level 0) from the front and look at its neighbours.
B is new: give it level 1 and add it to the back of the queue.
C is new: give it level 1 and add it to the back of the queue.
Take B (level 1) from the front and look at its neighbours.
D is new: give it level 2 and add it to the back of the queue.
Take C (level 1) from the front and look at its neighbours.
E is new: give it level 2 and add it to the back of the queue.
Take D (level 2) from the front and look at its neighbours.
F is new: give it level 3 and add it to the back of the queue.
Take E (level 2) from the front and look at its neighbours.
Take F (level 3) from the front and look at its neighbours.
The queue is empty. Every level was finished before the next began, so each level is the fewest edges from A.
Result. Visiting order A, B, C, D, E, F. The highlighted edges (each vertex to its parent) form the BFS tree.
BFS with an adjacency list
from collections import deque
def bfs(adj, s):
level = {s: 0} # also serves as the "found" set
parent = {s: None}
q = deque([s])
while q:
u = q.popleft() # O(1); list.pop(0) would cost O(n)
for v in adj[u]:
if v not in level: # mark when you ENQUEUE, so v enters only once
level[v] = level[u] + 1
parent[v] = u
q.append(v)
return level, parent
Why the first level is the fewest edges. At any moment the queue holds some vertices of level $k$ followed only by vertices of level $k+1$. So all of level $k$ is processed before any of level $k+1$. A vertex is therefore found from the earliest level that touches it. If a shorter route existed, a vertex on a lower level would have found it first.
Worked example: Rebuild a path from the parents
Problem.
Using the run above, give a path from A to F with the fewest edges.
Idea.
Walk from F back to its parent until you reach the start, then reverse.
- parent(F) = D.
- parent(D) = B.
- parent(B) = A, the start.
Answer.
A, B, D, F: 3 edges (A, C, E, F is just as short; BFS keeps the one found first).
Common mistake.
Reading the visiting order as if it were a path. A, B, C, D, E, F is not a walk in the graph.
Cost. Each vertex enters the queue once. When it leaves, its neighbours are scanned once. With lists the scans add up to the sum of degrees, so $O(V+E)$. With a matrix each scan reads a whole row, so $O(V^2)$.
Worked example: Weights break the promise
Problem.
Edges S–T of weight 10, S–M of weight 1 and M–T of weight 1. What does BFS from S report for T, and what is the cheapest cost?
Idea.
BFS counts edges and never reads weights.
- BFS finds T directly from S: level 1, using the edge of weight 10.
- The route S, M, T has 2 edges but costs 2.
Answer.
BFS: 1 edge (cost 10). Cheapest cost: 2.
Common mistake.
Using BFS for weighted shortest paths. It is correct only when every edge costs the same.
- Marking a vertex when it leaves the queue instead of when it joins: it can be queued many times.
- Using a stack instead of a queue: that changes the search into a depth-first style order.
- Forgetting that unreachable vertices never get a level.
Two ideas, both in the shortest-paths lesson: running BFS from every vertex when all weights are equal, and replacing a weight-w edge by w unit edges.
Queue in, level by level.
| Step | Method for any exam question |
|---|---|
| 1 | Write the adjacency lists in the stated order. |
| 2 | Keep a queue row; take from the front, add new vertices at the back. |
| 3 | Record level and parent at the moment of discovery. |
3. Depth-first search (DFS): go deep, then back up
Walk to an unvisited neighbour, from there to another, and keep going. At a dead end, step back and try the next neighbour.
The search that follows one path as far as it can before backing up, and the numbers it can record on the way.
The question this lesson answers. What does a depth-first walk tell us about the shape of a graph?
This is week 4 groundwork. Try the questions at the end first; if you get them all, move on.
Exploring a maze with a ball of string: go forward while there is a new passage; at a dead end, follow the string back to the last junction.
visit($u$): mark $u$ visited and note its pre number. For each neighbour $v$ of $u$ that is not visited: visit($v$). When no neighbour is left, note the post number of $u$ and return. One counter supplies both numbers.
Recursive DFS with pre and post numbers
def dfs(adj):
pre, post, parent = {}, {}, {}
clock = 0
def visit(u):
nonlocal clock
pre[u] = clock; clock += 1
for v in adj[u]:
if v not in pre:
parent[v] = u
visit(v) # u waits here until v is completely finished
post[u] = clock; clock += 1
for s in adj: # restart, so every piece of the graph is covered
if s not in pre:
parent[s] = None
visit(s)
return pre, post, parent
Graph used here (directed; neighbours in alphabetical order):
A: B, C, D B: D C: D D: E E: B
DFS from A, with the call stack
Enter A: pre(A) = 0. Push it on the call stack.
Enter B: pre(B) = 1. Push it on the call stack.
Enter D: pre(D) = 2. Push it on the call stack.
Enter E: pre(E) = 3. Push it on the call stack.
Look at E→B: B is still on the stack, so this is a back edge: the graph has a cycle.
Every edge out of E is done: post(E) = 4. Pop it and return to D.
Every edge out of D is done: post(D) = 5. Pop it and return to B.
Every edge out of B is done: post(B) = 6. Pop it and return to A.
Enter C: pre(C) = 7. Push it on the call stack.
Look at C→D: D finished before C was entered, so this is a cross edge.
Every edge out of C is done: post(C) = 8. Pop it and return to A.
Look at A→D: D is a finished descendant of A, so this is a forward edge.
Every edge out of A is done: post(A) = 9. Pop it.
The stack is empty. A call's [pre, post] interval sits inside its caller's interval.
| vertex | pre | post | interval |
|---|---|---|---|
| A | 0 | 9 | [0, 9] |
| B | 1 | 6 | [1, 6] |
| C | 7 | 8 | [7, 8] |
| D | 2 | 5 | [2, 5] |
| E | 3 | 4 | [3, 4] |
Why the intervals nest or stay apart. A call started inside visit($u$) must return before visit($u$) can return. So if $v$ is reached from inside $u$, its whole interval lies inside that of $u$. Otherwise the two intervals do not overlap at all. They never half-overlap.
| Edge u→v | Test on the intervals | In this run |
|---|---|---|
| tree | $v$ first discovered from $u$ | A→B, B→D, D→E, A→C |
| forward | $v$ inside $u$, not a tree edge | A→D |
| back | $u$ inside $v$ ($v$ is an ancestor) | E→B |
| cross | intervals apart | C→D |
A directed graph has a cycle exactly when DFS finds a back edge. A back edge $u\to v$ plus the tree path from $v$ down to $u$ is a cycle (here $B,D,E,B$). Forward and cross edges alone do not make one.
Undirected graphs. Every edge to an already visited vertex other than the one you came from closes a cycle. To find connected components, number each restart of the outer loop: all vertices reached from one start belong to one component.
Worked example: Count the components
Problem.
Undirected graph on vertices 0 to 6 with edges 0–1, 1–2, 3–4. How many connected components?
Idea.
Each new start of the outer loop is a new component.
- Start 0 reaches 0, 1, 2.
- Start 3 reaches 3, 4.
- Start 5 reaches only 5.
- Start 6 reaches only 6.
Answer.
4 components.
Common mistake.
Forgetting vertices with no edge to others: 6 is a component on its own.
| BFS | DFS | |
|---|---|---|
| structure | queue | stack (the recursion) |
| gives fewest edges | yes | no |
| typical use | distances in unweighted graphs | cycles, ordering, structure |
| cost with lists | $O(V+E)$ | $O(V+E)$ |
| cost with matrix | $O(V^2)$ | $O(V^2)$ |
- Calling every edge to a visited vertex a back edge. In a directed graph the target must still be on the stack.
- Assuming the DFS path to a vertex is the shortest one.
- Forgetting the outer loop, so unreachable vertices are never visited.
Back edge means cycle.
| Step | Method for any exam question |
|---|---|
| 1 | Follow the first unvisited neighbour; keep the stack written down. |
| 2 | Number on entry and on exit with one counter. |
| 3 | Classify an edge by comparing the two intervals. |
4. Shortest paths: the big picture and relaxation
A shortest path is the cheapest route between two vertices. Every algorithm keeps a guess for each distance and repeatedly lowers a guess when it finds a cheaper route (relaxation).
What a shortest path is, why there are several algorithms, and the one operation they all share: relaxation.
The question this lesson answers. How do distance estimates become correct?
| New word | Meaning |
|---|---|
| weight | the cost of an edge |
| distance | the cost of the cheapest path |
| relax | lower an estimate when a cheaper route is found |
Noting travel times on a map: whenever you hear of a quicker way to a town, cross out the old time and write the new one.
Vertices, edges and the two storage forms come from the earlier lesson on graphs. Here every edge $u\to v$ carries a weight, and the list stores pairs: $\texttt{adj[u] = [(v, w), ...]}$.
A weighted graph has vertices (places) and edges (roads) with a cost (weight) on each edge. The cost of a path is the sum of its edge weights. The shortest path from a source $s$ to a vertex $v$ is the path with the smallest cost; its cost is the distance $d(s,v)$.
Shortest means smallest total weight, not fewest edges. A path with 4 cheap edges can beat a path with 1 expensive edge. (PYQ Apr 2026 Q1 tests exactly this.)
Relaxation is the only move. Keep an array dist[v] (best known cost to $v$, start ∞ except dist[s]=0). To relax an edge $u\to v$ with weight $w$:
Relaxation
def relax(u, v, w, dist):
if dist[u] + w < dist[v]: # going through u is cheaper than what we know
dist[v] = dist[u] + w # lower the guess
return True
return False
Line 2 asks: "is the route that reaches $u$ and then takes edge $(u,v)$ cheaper than my current best route to $v$?" Line 3 lowers the guess. A guess is never lower than the truth, because it always comes from a real path.
Triangle inequality for shortest paths. For every edge $u\to v$ of weight $w$: $d(s,v)\le d(s,u)+w$. All the algorithms stop when no edge can be relaxed any more.
Why it works. Each relaxation can only lower an estimate to the length of a real path, so estimates approach the true value from above.
Watch a guess get better
Reaching S costs 0. Everything else is ∞, meaning no route has been found yet.
0 + 6 = 6 is less than ∞, so dist[A] drops to 6.
0 + 2 = 2 is less than ∞, so dist[B] drops to 2.
2 + 3 = 5 is less than 6, so dist[A] drops to 5. A two-edge route beat the direct road.
No edge can lower anything now, so these are the true distances. Green edges form the shortest routes.
The only difference between the algorithms is the order of relaxing. Dijkstra picks a clever order, so each edge is needed once. Bellman-Ford makes no assumption about order, so it repeats all edges several times. Floyd-Warshall relaxes every pair of vertices through one middle vertex at a time.
| Algorithm | Question it answers | Negative edges? | Greedy or DP? | Time |
|---|---|---|---|---|
| Dijkstra | one source to all vertices | no | greedy | $O((V+E)\log V)$ with a min-heap |
| Bellman-Ford | one source to all vertices | yes (no negative cycle) | dynamic programming | $O(VE)$ |
| Floyd-Warshall | all pairs | yes (no negative cycle) | dynamic programming | $O(V^3)$ |
| BFS | one source, all edges equal | no weights | level by level | $O(V+E)$ |
Negative cycle = a cycle whose weights add to less than 0. Going around it again and again makes the cost smaller forever, so a shortest path does not exist. Bellman-Ford and Floyd-Warshall can detect it; Dijkstra cannot.
Worked example: Relax by hand
Problem.
dist[u]=5, edge u→v weight 3, dist[v]=9. Relax it. Then relax again with dist[v]=7.
Idea.
Compare dist[u]+w with dist[v].
- First: 5+3=8 < 9, so dist[v] becomes 8.
- Second: 8 < 7 is false, so dist[v] stays 7.
Answer.
8, then 7.
Common mistake.
Replacing the guess even when the new route is worse.
Worked example: Going round for ever
Problem.
A cycle has edge weights $2$, $-4$ and $1$. What happens to path lengths through it?
Idea.
Add the weights around the cycle.
- The total is $-1$.
- Each extra lap lowers the length by 1.
Answer.
There is no shortest path: lengths decrease without limit.
Common mistake.
Answering with the length after a single lap.
Worked example: Choose the algorithm from the wording
Problem.
Pick the algorithm: (a) road lengths, from one depot to every town; (b) one source, some edges negative; (c) the distance between every pair of towns; (d) fewest hops in a network where every link costs the same.
Idea.
Ask two things: one source or all pairs? Can a weight be negative?
- (a) One source, lengths are never negative: Dijkstra.
- (b) One source with negative edges: Bellman-Ford.
- (c) All pairs: Floyd-Warshall.
- (d) Equal costs, so fewest edges is cheapest: BFS.
Answer.
Dijkstra, Bellman-Ford, Floyd-Warshall, BFS.
Common mistake.
Using Dijkstra the moment you see the word shortest, without checking the weights.
| Common mistake | Correction |
|---|---|
| shortest path = fewest vertices | shortest = smallest total weight |
| a negative edge always means a negative cycle | no: a negative cycle needs a cycle with total below 0 |
| Bellman-Ford and Floyd-Warshall are greedy | dynamic programming |
| Dijkstra works with negative edges | not guaranteed |
Can there be more than one shortest path? Yes. Two different routes can have the same total, even when every edge weight is different. Take $S\to A$ 1, $A\to T$ 4, $S\to B$ 2, $B\to T$ 3. All four weights differ, yet both routes to $T$ cost 5. The distance is always a single number; the path that achieves it may not be.
Distinct edge weights guarantee a unique minimum spanning tree. They guarantee nothing about shortest paths being unique.
Worked example: Count the shortest paths
Problem.
Edges $S\to A$ 1, $S\to B$ 1, $A\to C$ 2, $B\to C$ 2, $C\to T$ 3, $A\to T$ 5. How many different shortest paths go from $S$ to $T$?
Idea.
Keep a count beside each distance: a cheaper route replaces the count, an equal route adds to it.
- $d(S)=0$, count 1. $d(A)=1$ and $d(B)=1$, count 1 each.
- $C$ is reached with cost 3 through $A$ and through $B$: $d(C)=3$, count $1+1=2$.
- $T$ through $C$ costs $3+3=6$ with the 2 paths of $C$. $T$ through $A$ costs $1+5=6$ with 1 path.
- Both cost 6, so add them: count 3.
Answer.
Distance 6, with 3 shortest paths.
Common mistake.
Stopping at the first path that reaches the smallest cost.
Turning weights into extra vertices. If all weights are positive whole numbers, replace an edge of weight $w$ by a chain of $w$ edges of weight 1 (adding $w-1$ new vertices). Now every edge costs the same, so BFS finds the correct distances. It is correct but wasteful: the new graph has as many edges as the sum of all weights. One road of weight 1000000 becomes a million edges. BFS then costs $O(V+\sum w)$, which depends on how big the numbers are, while Dijkstra's $O((V+E)\log V)$ does not. So the trick works but is less efficient than Dijkstra.
| All pairs, every edge the same weight | Cost | Comment |
|---|---|---|
| BFS from every vertex | $O(V(V+E))$ | cheapest |
| Dijkstra from every vertex | $O(V(V+E)\log V)$ | the heap adds a factor $\log V$ for nothing |
| Bellman-Ford from every vertex | $O(V^2E)$ | slowest on most graphs |
| Floyd-Warshall | $O(V^3)$ | no gain from equal weights |
- Check two words first: directed and negative. They decide which edges you may use and which algorithm is safe.
- Write distances in one row and update it as you relax, so no value is forgotten.
- A distance estimate only ever goes down.
Relax: take it only if it is cheaper.
| Step | Method for any exam question |
|---|---|
| 1 | Start with 0 at the source. |
| 2 | For an edge, compare the new route with the current estimate. |
| 3 | Keep the smaller. |
5. Dijkstra's algorithm, step by step
Repeat: pick the unvisited vertex with the smallest known distance, finalise it, and relax its outgoing edges.
The greedy single-source shortest-path algorithm for graphs with non-negative weights.
The question this lesson answers. Why can the closest unfinished vertex be fixed for good?
| New word | Meaning |
|---|---|
| finalised | a vertex whose distance will not change again |
| frontier | reached but not yet finalised vertices |
| min-heap | a structure that returns the smallest estimate quickly |
Water poured at the source spreads along pipes. The place it reaches next is always the nearest dry one, and once wet it cannot be reached any earlier.
Idea (the greedy step). Among the vertices not yet finalised, the one with the smallest known distance cannot be improved any more: any other route to it must first pass through some unfinalised vertex whose distance is already at least as large, and then add a non-negative edge. So we can finalise it (visit it) and move on.
Dijkstra. (1) dist[s]=0, all others ∞, no vertex visited. (2) Pick the unvisited vertex $u$ with the smallest dist. (3) Mark $u$ visited. (4) For every edge $u\to v$: relax. (5) Repeat until all reachable vertices are visited.
The run below uses these directed edges: S→A 4, S→B 1, B→A 2, B→C 5, A→C 1, C→D 3.
Dijkstra on a small graph from S
dist[S] = 0 and every other distance is ∞. Nothing is finalised yet.
S has the smallest distance among unfinished vertices, so Dijkstra declares 0 final.
0 + 4 = 4 is less than ∞, so update dist[A] to 4.
0 + 1 = 1 is less than ∞, so update dist[B] to 1.
B has the smallest distance among unfinished vertices, so Dijkstra declares 1 final.
1 + 2 = 3 is less than 4, so update dist[A] to 3.
1 + 5 = 6 is less than ∞, so update dist[C] to 6.
A has the smallest distance among unfinished vertices, so Dijkstra declares 3 final.
3 + 1 = 4 is less than 6, so update dist[C] to 4.
C has the smallest distance among unfinished vertices, so Dijkstra declares 4 final.
4 + 3 = 7 is less than ∞, so update dist[D] to 7.
D has the smallest distance among unfinished vertices, so Dijkstra declares 7 final.
All reachable vertices are final: S=0, A=3, B=1, C=4, D=7. Green edges form the shortest-path tree.
The same run as a table
| step | visit | its distance | relaxed | distances after |
|---|---|---|---|---|
| 1 | S | 0 | A→4, B→1 | S=0, A=4, B=1, C=∞, D=∞ |
| 2 | B | 1 | A→3, C→6 | S=0, A=3, B=1, C=6, D=∞ |
| 3 | A | 3 | C→4 | S=0, A=3, B=1, C=4, D=∞ |
| 4 | C | 4 | D→7 | S=0, A=3, B=1, C=4, D=7 |
| 5 | D | 7 | - | S=0, A=3, B=1, C=4, D=7 |
Claim: every visited vertex has its true distance. It holds at the start (only $s$). Let $u$ be the unvisited vertex with the smallest dist, and take any route from $s$ to $u$. Somewhere it leaves the visited set for the first time, by an edge $x\to y$ with $x$ visited and $y$ not. Because $x$ is correct and its edges were relaxed, reaching $y$ this way costs at least $dist[y]$, and $dist[y]\ge dist[u]$ since $u$ was the smallest. The rest of the route, from $y$ to $u$, adds only non-negative weights. So the whole route costs at least $dist[u]$: nothing can beat it.
Why negative edges break it. Dijkstra never looks at a visited vertex again. A negative edge discovered later could give a cheaper route to a vertex that is already finalised, and the algorithm would miss it. (PYQ statement A in Aug 2026 Q1 says exactly this.)
Worked example: One negative edge is enough
Problem.
Edges $S\to A$ 2, $S\to B$ 3, $B\to A$ $-2$, $A\to C$ 1. Standard Dijkstra never revisits a finalised vertex. What does it report for $C$, and what is the true distance?
Idea.
Watch when $A$ is finalised.
- $A$ is finalised at distance 2, before $B$.
- $C$ is then set to 3.
- The route $S,B,A$ costs 1, found too late.
- So the true distance to $C$ is 2.
Answer.
Reports 3; the true distance is 2.
Common mistake.
Assuming the late cheaper route is passed on.
Step through it: one negative edge fools Dijkstra
dist[S] = 0 and every other distance is ∞. Nothing is finalised yet.
S has the smallest distance among unfinished vertices, so Dijkstra declares 0 final.
0 + 2 = 2 is less than ∞, so update dist[A] to 2.
0 + 3 = 3 is less than ∞, so update dist[B] to 3.
A has the smallest distance among unfinished vertices, so Dijkstra declares 2 final.
2 + 1 = 3 is less than ∞, so update dist[C] to 3.
B has the smallest distance among unfinished vertices, so Dijkstra declares 3 final.
3 + (-2) = 1 would beat dist[A] = 2, but A is already final. Dijkstra never reopens it.
C has the smallest distance among unfinished vertices, so Dijkstra declares 3 final.
Dijkstra ends with dist[C] = 3, but S→B→A→C costs 3 − 2 + 1 = 2. A was finalised too early.
Dijkstra with a min-heap
import heapq
def dijkstra(adj, s): # adj[u] = list of (v, w)
dist = {u: float("inf") for u in adj}
dist[s] = 0
heap = [(0, s)] # (distance, vertex)
visited = []
while heap:
d, u = heapq.heappop(heap) # smallest known distance
if u in visited:
continue # stale entry, skip
visited.append(u) # u is finalised
for v, w in adj[u]:
if v not in visited and d + w < dist[v]: # relax u->v
dist[v] = d + w
heapq.heappush(heap, (dist[v], v))
return dist, visited
Line-by-line: lines 4-5 set the starting guesses; line 6 puts the source in the heap; line 9 always returns the smallest known distance; lines 10-11 skip vertices already finalised (the heap may hold old, larger entries); line 12 finalises $u$; lines 13-16 relax each outgoing edge that leads to an unfinished vertex and push the improved distance. A finished vertex is never updated again.
Python’s heap cannot lower an entry in place, so an improved distance is pushed again. In the run above A is pushed with 4 and later with 3. The 3 comes out first; when the 4 appears, A is already visited, so it is skipped.
Cost. With a min-heap: each vertex is finalised once and each edge is relaxed at most once; every heap operation costs $O(\log V)$. Total $O((V+E)\log V)$ (the PYQ writes $O((m+n)\log n)$). With a plain array scanned for the minimum: $O(V^2)$.
| Implementation | Find minimum | Total time | Best for |
|---|---|---|---|
| array scan | $O(V)$ each, $V$ times | $O(V^2)$ | dense graphs ($E\approx V^2$) |
| binary min-heap | $O(\log V)$ each | $O((V+E)\log V)$ | sparse graphs |
| BFS (all weights 1) | queue | $O(V+E)$ | unweighted graphs |
| Statement | True? | Reason |
|---|---|---|
| picks the unvisited vertex with the smallest known distance | true | the greedy rule |
| the path always has the fewest vertices | false | it minimises total weight |
| adding the same number to every edge keeps the shortest path | false | paths with more edges grow more |
| multiplying every edge by a positive number keeps the shortest path | true | every path cost scales by the same factor |
| may fail with negative edges | true | never reconsiders a visited vertex |
Ties. When two unvisited vertices have the same smallest distance, the PYQ tells you the rule (usually alphabetical). The final distances do not depend on the tie, but the visiting order does.
Worked example: Order with a tie
Problem.
From P: edges P→Q 1, P→R 1, Q→S 2, R→S 1. Order with ties alphabetical.
Idea.
Q and R tie at distance 1.
- Visit P (0): Q=1, R=1.
- Tie: visit Q first (alphabetical). Relax Q→S: S=3.
- Visit R (1): R→S gives 2 < 3, so S=2.
- Visit S.
Answer.
P, Q, R, S with S=2.
Common mistake.
Forgetting that S improved after visiting R.
| Common mistake | Correction |
|---|---|
| picking the smallest edge weight instead of the smallest distance | smallest known total distance from the source |
| not relaxing all outgoing edges | relax every edge of the visited vertex |
| ignoring the tie rule | follow the alphabetical rule given |
| using it on negative edges | use Bellman-Ford |
Fix the nearest, then relax.
| Step | Method for any exam question |
|---|---|
| 1 | Pick the smallest unfinished distance. |
| 2 | Fix it. |
| 3 | Relax its outgoing edges. |
6. Bellman-Ford and Floyd-Warshall
Bellman-Ford relaxes every edge $V-1$ times (one source). Floyd-Warshall tries every vertex as a middle stop (all pairs).
Two dynamic-programming shortest-path algorithms that accept negative edges, and how they detect a negative cycle.
The question this lesson answers. What if some edges are negative, or all pairs are wanted?
| New word | Meaning |
|---|---|
| round | one pass that relaxes every edge |
| negative cycle | a cycle whose total weight is below 0 |
| intermediate vertex | a stop allowed in the middle of a path |
Bellman-Ford is passing news person to person, one step per round. Floyd-Warshall is asking, for each town in turn, whether stopping there shortens any trip.
Bellman-Ford idea. A shortest path that has no repeated vertex uses at most $V-1$ edges. So relax every edge once (a round), and repeat for $V-1$ rounds: after round $k$, every shortest path with at most $k$ edges is correct. This is dynamic programming on the number of edges, not a greedy rule.
Why exactly $V-1$ rounds? A shortest path never visits a vertex twice (a loop would only add cost when there is no negative cycle). With $V$ vertices it therefore has at most $V-1$ edges. Round 1 is guaranteed to get the first edge of that path right, round 2 the second, and so on. After round $V-1$ the whole path is right, whatever order the edges were listed in.
Bellman-Ford
def bellman_ford(n, edges, s): # edges = [(u, v, w)]
dist = [float("inf")] * n
dist[s] = 0
for _ in range(n - 1): # V-1 rounds
for u, v, w in edges:
if dist[u] + w < dist[v]: # relax
dist[v] = dist[u] + w
for u, v, w in edges: # one extra round
if dist[u] + w < dist[v]:
return None # negative cycle reachable from s
return dist
Lines 4-7 are the $V-1$ rounds (each does $E$ relaxations: total $O(VE)$). Lines 8-10 are the negative-cycle test: if one more relaxation still lowers a distance, then some cycle keeps lowering it, so a negative cycle exists.
Bellman-Ford passes when the edge order is unlucky
dist[S] = 0, the rest ∞. Every round relaxes the edges in this order: A→C, B→A, S→A, S→B, B→C.
0 + (4) = 4 is less than ∞: update dist[A].
0 + (5) = 5 is less than ∞: update dist[B].
5 + (6) = 11 is less than ∞: update dist[C].
Round 1 changed 3 values (edges that cannot improve anything are skipped here). Paths with up to 1 edge are now correct.
4 + (2) = 6 is less than 11: update dist[C].
5 + (-3) = 2 is less than 4: update dist[A].
Round 2 changed 2 values (edges that cannot improve anything are skipped here). Paths with up to 2 edges are now correct.
2 + (2) = 4 is less than 6: update dist[C].
Round 3 changed 1 value (edges that cannot improve anything are skipped here). Paths with up to 3 edges are now correct.
One extra pass improves nothing, so there is no negative cycle and these distances are final.
The same graph in a lucky order: S→A, S→B, B→A, A→C, B→C
| round | distances after the round |
|---|---|
| 1 | S=0, A=2, B=5, C=4 |
| 2 | S=0, A=2, B=5, C=4 |
| 3 | S=0, A=2, B=5, C=4 |
Result: S=0, A=2 (via S→B→A, 5−3), B=5, C=4. The extra round changes nothing, so no negative cycle.
Detection rule (exam favourite). After exactly $V-1$ rounds, if one more pass can still reduce a distance, a negative cycle is present. A negative edge alone is not a negative cycle, and "several shortest paths exist" says nothing about cycles.
Floyd-Warshall idea. Build a table $SP^k[i][j]$ = shortest distance from $i$ to $j$ using only the first $k$ vertices as intermediate stops. Either the best path avoids vertex $k$, or it goes $i\to k\to j$:
$SP^k[i,j]=\min\big(SP^{k-1}[i,j],\;SP^{k-1}[i,k]+SP^{k-1}[k,j]\big)$. Three nested loops over $k,i,j$: time $O(V^3)$, memory $O(V^2)$.
Why it works. After round k of Floyd-Warshall, every pair has its best route using only the first k vertices as stops; after the last round all stops are allowed.
Floyd-Warshall
def floyd(d): # d[i][j] = edge weight, 0 on diagonal, inf if no edge
n = len(d)
for k in range(n): # allow k as an intermediate vertex
for i in range(n):
for j in range(n):
if d[i][k] + d[k][j] < d[i][j]:
d[i][j] = d[i][k] + d[k][j]
return d
Floyd-Warshall result for the same graph
| from \ to | S | A | B | C |
|---|---|---|---|---|
| S | 0 | 2 | 5 | 4 |
| A | ∞ | 0 | ∞ | 2 |
| B | ∞ | -3 | 0 | -1 |
| C | ∞ | ∞ | ∞ | 0 |
Diagonal test. $d[i][i]$ starts at 0. If it ends negative, vertex $i$ lies on a cycle of negative total weight, so the graph has a negative cycle. (In the demo graph the diagonal is all 0.)
| Property | Bellman-Ford | Floyd-Warshall |
|---|---|---|
| answers | one source to all | all pairs |
| negative edges | yes | yes |
| negative cycle | detects (extra round) | detects (negative diagonal) |
| time | $O(VE)$ | $O(V^3)$ |
| technique | dynamic programming | dynamic programming |
| disconnected graph | fine (unreachable = ∞) | fine |
Worked example: Detect a cycle
Problem.
Edges S→A 1, A→B −3, B→A 1. Is there a negative cycle reachable from S?
Idea.
Add the cycle weights.
- The cycle A→B→A has weight −3+1 = −2 < 0.
- Distances keep falling on every round.
Answer.
Yes. The extra relaxation round still lowers a distance.
Common mistake.
Saying no because only one edge is negative.
Worked example: Cost comparison
Problem.
A graph has V=100 vertices and E=300 edges. Compare Bellman-Ford from one source with Floyd-Warshall.
Idea.
$VE$ versus $V^3$.
- Bellman-Ford: $100\cdot300=30{,}000$.
- Floyd-Warshall: $100^3=1{,}000{,}000$.
Answer.
Bellman-Ford is about 33 times cheaper for one source; Floyd-Warshall is for all pairs.
Common mistake.
Quoting Floyd-Warshall as $O(V^2)$.
| Common mistake | Correction |
|---|---|
| Floyd-Warshall is $O(V^2)$ | $O(V^3)$ |
| both are greedy | both are dynamic programming |
| Bellman-Ford fails on disconnected graphs | unreachable vertices simply stay ∞ |
| negative edge means negative cycle | needs a cycle with negative total |
Edge order matters for how fast the distances settle, never for the final answer: after $V-1$ rounds every order gives the same result.
Floyd-Warshall on 3 vertices: the table after each allowed stop
| stage | d[1][2] | d[1][3] | d[2][1] | d[2][3] | d[3][1] | d[3][2] | improved |
|---|---|---|---|---|---|---|---|
| direct edges only | 4 | 11 | ∞ | 2 | 3 | ∞ | - |
| allow stop 1 | 4 | 11 | ∞ | 2 | 3 | 7 | 3→2 via 1 |
| allow stop 2 | 4 | 6 | ∞ | 2 | 3 | 7 | 1→3 via 2 |
| allow stop 3 | 4 | 6 | 5 | 2 | 3 | 7 | 2→1 via 3 |
Worked example: Negative edge, no negative cycle
Problem.
Edges S→A 2, S→B 3, B→A −2. Dijkstra and Bellman-Ford distance to A?
Idea.
Dijkstra finalises A before seeing B→A.
- Dijkstra visits A (2) before B (3) and never revisits it: A=2.
- Bellman-Ford relaxes B→A: A = 3−2 = 1.
Answer.
Dijkstra 2 (wrong), Bellman-Ford 1 (right).
Common mistake.
Believing a negative edge alone means "no shortest path".
Worked example: Edge order changes the work
Problem.
A path $s,a,b,c$ has unit edges. How many rounds improve distances if edges are scanned from the start of the path, and how many if scanned from its end?
Idea.
In one round a distance can travel along several edges only if they come in order.
- In path order, one round updates $a$, $b$ and $c$.
- In reverse order each round updates one more vertex.
Answer.
1 round against 3.
Common mistake.
Assuming every order needs the same number of improving rounds.
One Floyd-Warshall round by hand. To do round $k$, copy row $k$ and column $k$ unchanged. For every other cell $(i,j)$, add the number in column $k$ of row $i$ to the number in row $k$ of column $j$. Keep the smaller of that sum and the old cell. Cells on the diagonal are checked too: a negative one signals a negative cycle.
Worked example: Fill one round of the table
Problem.
Rows are "from", columns are "to", vertices 1, 2, 3. Current table: row 1 = (0, 8, 3), row 2 = (2, 0, ∞), row 3 = (∞, 4, 0). Now allow vertex 1 as a middle stop.
Idea.
Row 1 and column 1 stay. Compare each other cell with the route through vertex 1.
- Cell (2,3): old ∞. Through 1: $d[2][1]+d[1][3]=2+3=5$. New value 5.
- Cell (3,2): old 4. Through 1: $d[3][1]=∞$, so no improvement.
- Diagonal cells (2,2) and (3,3) stay 0, since $2+8$ and $∞+3$ are not smaller.
Answer.
Row 1 = (0, 8, 3), row 2 = (2, 0, 5), row 3 = (∞, 4, 0).
Common mistake.
Using the new table of a later round, or changing row $k$ and column $k$.
- For Floyd-Warshall options, check the order of the indices: the formula is $\min(d[i][j],\,d[i][k]+d[k][j])$.
- "Dynamic programming" is right for both algorithms; "greedy" is a distractor.
- Bellman-Ford only: stop early by hand, because if a full round changes nothing, later rounds change nothing. Do not do this in Floyd-Warshall.
Rounds of edges, or rounds of middle vertices.
| Step | Method for any exam question |
|---|---|
| 1 | Bellman-Ford: relax all edges, V minus 1 times. |
| 2 | One more improvement means a negative cycle. |
| 3 | Floyd-Warshall: allow one more middle vertex each round. |
7. Minimum spanning trees: cut and cycle rules, Prim, Kruskal
A spanning tree joins all $V$ vertices using $V-1$ edges and no cycle. The MST is the one with the smallest total weight. Greedy works: always take the cheapest safe edge.
How to connect all vertices with the smallest total edge weight, and which edges must or must not be in it.
The question this lesson answers. Which edges connect everything at the least total cost?
Laying cable to connect every village for the least money: buy the cheapest link that joins something not yet joined.
A spanning tree of a connected graph uses all vertices and exactly $V-1$ edges with no cycle. Among all spanning trees, the minimum spanning tree (MST, MCST) has the smallest total weight. If all edge weights are distinct the MST is unique; with ties there can be several (all with the same total weight).
A cut splits the vertices into two non-empty groups. The edges with one end in each group cross it.
The lightest edge crossing any cut belongs to some MST, and to every MST if the weights are distinct.
Why. Take a minimum tree $T$ that leaves out this lightest crossing edge $e$. Adding $e$ to $T$ makes exactly one cycle. The cycle crosses from one group to the other through $e$, so it must cross back through another crossing edge $f$. Remove $f$: the result is again a spanning tree, with weight $T+e-f$. Since $e$ is the lightest crossing edge, $e\le f$, so the new tree is no heavier. Therefore some MST contains $e$. If $e<f$ strictly, the new tree is cheaper, so $T$ was not minimum.
An edge that is strictly heavier than every other edge of some cycle is in no MST.
Why. Suppose a minimum tree uses such an edge $f$. Removing $f$ splits the tree into two pieces. The rest of the cycle still joins the two ends of $f$, so one of its edges $e$ crosses between the pieces. Adding $e$ rejoins them into a spanning tree, and $e<f$ makes it cheaper than a minimum tree: impossible.
What is not guaranteed. The lightest edge between $X$ and $Y$ need not lie on every path from $s$ to $t$ (other routes exist). The lightest edge of a cycle need not be in the MST. The heaviest edge of the whole graph is excluded only if it lies on a cycle: a bridge (an edge whose removal disconnects the graph) is in every spanning tree.
Worked example: A cheap tree is not a short route
Problem.
A triangle has $s\!-\!a$ 2, $a\!-\!b$ 2 and $s\!-\!b$ 3. Compare the path from $s$ to $b$ in the minimum spanning tree with the shortest path.
Idea.
The tree minimises the total, not each route.
- The tree takes the two edges of weight 2.
- In the tree, $s$ to $b$ costs 4.
- The direct edge costs 3.
Answer.
4 in the tree, 3 shortest.
Common mistake.
Reading shortest distances from a minimum spanning tree.
Prim's algorithm. Start with one vertex. Repeatedly add the cheapest edge that joins a vertex inside the tree to a vertex outside it. Stop after $V-1$ edges. It does not sort all edges first. The starting vertex changes the visiting order but not the total weight.
Each step of Prim is the cut rule, with the cut "in the tree" against "not yet in the tree". That is why every edge it takes is safe.
Prim on a 6-vertex graph, start A
The tree holds only A. The queue lists every edge that leaves the tree.
A–C is the cheapest edge from inside the tree to outside it. The cut property says it is safe.
C joins the tree (total 2). Edges that now have both ends inside drop out of the queue.
C–B is the cheapest edge from inside the tree to outside it. The cut property says it is safe.
B joins the tree (total 3). Edges that now have both ends inside drop out of the queue.
B–D is the cheapest edge from inside the tree to outside it. The cut property says it is safe.
D joins the tree (total 8). Edges that now have both ends inside drop out of the queue.
D–E is the cheapest edge from inside the tree to outside it. The cut property says it is safe.
E joins the tree (total 10). Edges that now have both ends inside drop out of the queue.
E–F is the cheapest edge from inside the tree to outside it. The cut property says it is safe.
F joins the tree (total 13). Edges that now have both ends inside drop out of the queue.
All vertices are connected using 5 edges, total weight 13.
Visiting order: A, C, B, D, E, F. Total weight 13. Edges taken: A–C(2), C–B(1), B–D(5), D–E(2), E–F(3).
Prim with a min-heap (same idea as Dijkstra, but keyed by edge weight)
import heapq
def prim(adj, s): # adj[u] = list of (v, w)
in_tree = {s}
heap = [(w, v) for v, w in adj[s]]
heapq.heapify(heap)
total = 0
while heap:
w, v = heapq.heappop(heap) # cheapest edge leaving the tree
if v in in_tree:
continue
in_tree.add(v)
total += w
for x, wx in adj[v]:
if x not in in_tree:
heapq.heappush(heap, (wx, x))
return total
The only difference from Dijkstra: Prim keys the heap by the single edge weight (line 9 pops $w$), while Dijkstra keys it by the total distance from the source. Both cost $O((V+E)\log V)$ with a heap.
Kruskal's algorithm. Sort all edges by weight. Go through them in order and add an edge if it does not create a cycle (check with disjoint sets, next section). Stop at $V-1$ edges. Time $O(E\log E)$.
Kruskal is safe for the same reason: when it takes an edge, that edge is the lightest one leaving the group at one of its ends. When it skips an edge, the edge closes a cycle in which nothing is heavier than it.
Kruskal on the same graph (total 13)
| # | edge | weight | decision and reason |
|---|---|---|---|
| 1 | B–C | 1 | take |
| 2 | A–C | 2 | take |
| 3 | D–E | 2 | take |
| 4 | E–F | 3 | take |
| 5 | A–B | 4 | skip: A, C, B already joins them |
| 6 | B–D | 5 | take: first link between {A,B,C} and {D,E,F} |
| 7 | D–F | 6 | skip: D, E, F already joins them |
| 8 | C–D | 8 | skip: C, B, D already joins them |
| 9 | C–E | 10 | skip: C, B, D, E already joins them |
Kruskal: accept an edge or reject a cycle
Sort all edges by weight. Every vertex starts in its own group.
Are B and C already in the same group?
Different groups, so take the edge and merge them. Total 1.
Are A and C already in the same group?
Different groups, so take the edge and merge them. Total 3.
Are D and E already in the same group?
Different groups, so take the edge and merge them. Total 5.
Are E and F already in the same group?
Different groups, so take the edge and merge them. Total 8.
Are A and B already in the same group?
A and B are already connected, so this edge would close a cycle: reject it.
Are B and D already in the same group?
Different groups, so take the edge and merge them. Total 13.
5 edges are taken, so we stop early. MST weight 13.
| Prim | Kruskal |
|---|---|
| grows one tree | grows a forest that merges |
| looks at edges leaving the tree | looks at edges in sorted order |
| no global sort | sorts all edges first |
| needs a heap or array | needs disjoint sets (DSU) |
| same total weight | same total weight |
When is the MST unique? Distinct weights guarantee it. The reverse is false: a graph with equal weights can still have only one MST. So look at each tie and ask whether it forces a choice: can one of the equal edges be swapped for the other and still leave a spanning tree of the same weight? If both are always taken, or both are always rejected, there is no choice.
| Equal weights sit on | Number of MSTs |
|---|---|
| two bridges (no cycle through either) | one: both are forced |
| two edges that are the strictly heaviest options of the same cycle | two: drop either one |
| the two cheapest edges, which cannot form a cycle alone | one: both are taken |
Take the weights from small to large. At each weight:
- Join the vertices that the lighter edges already connect into groups.
- Drop this weight's edges that lie inside one group.
- Count the ways to pick as many of the rest as possible without closing a cycle between groups.
Multiply the counts of all weights. If you may choose an unknown weight $x$ to get the most trees, try $x$ equal to each weight already present, because only ties add choices.
Worked example: Count tie group by tie group
Problem.
Edges: A–B 1; B–C, C–D, D–A all 3; B–E, C–E, D–E all 5; A–C 6. How many MSTs does the graph have, and what does each weigh?
Idea.
After each weight, redraw the connected groups.
- Weight 1: A–B is the only edge. Take it: 1 way. Groups: {A,B}, C, D, E.
- Weight 3: B–C, C–D and D–A now form a triangle between the groups {A,B}, C and D, although they were not a triangle before. Any 2 of the 3: 3 ways.
- Weight 5: only E is left outside, and B–E, C–E and D–E each reach it. Pick 1: 3 ways.
- Weight 6: everything is already connected, so A–C is never used.
Answer.
$1\times3\times3=9$ MSTs, each of weight $1+3+3+5=12$.
Common mistake.
Looking for cycles in the original drawing only. B–C, C–D and D–A compete because A and B are already joined.
Worked example: When you have to list: two cycles that share an edge
Problem.
A triangle P, Q, R and a 4-cycle P, R, S, T share the edge P–R. All six edges have weight 4. How many MSTs are there?
Idea.
A tree on 5 vertices has 4 edges. Count all choices of 4, then remove those that contain a cycle.
- Choices of 4 edges from 6: $\binom64=15$.
- Choices containing the triangle P,Q,R: its 3 edges plus any 1 of the other 3, so 3.
- Choices containing the 4-cycle P,R,S,T: exactly those 4 edges, so 1.
- The outer cycle has 5 edges, so 4 edges cannot contain it. No choice was counted twice.
Answer.
$15-3-1=11$ MSTs.
Common mistake.
Multiplying 3 for the triangle by 4 for the square. The cycles share edge P–R, so the choices are not independent.
Your turn, one weight at a time. Decide each step before opening it.
Worked example: An unknown weight: make the total come out right
Problem.
Edges $P\!-\!Q$ 2, $Q\!-\!R$ 6, $R\!-\!S$ 3, $P\!-\!R$ $X$. For which $X$ is the MST weight 9?
Idea.
First build the tree without the unknown edge, then see which edge it can replace.
- Without $P\!-\!R$ the tree is forced: $2+6+3=11$.
- $P\!-\!R$ closes the cycle $P,Q,R$. It replaces the heaviest edge there, 6, when $X<6$.
- The total is then $11-6+X=5+X$.
- $5+X=9$ gives $X=4$, which is indeed below 6.
Answer.
$X=4$
Common mistake.
Solving the equation and not checking that $X$ really replaces the old edge.
Worked example: Make the MST as heavy as possible
Problem.
Edges: A–B, A–C, B–C, B–D, C–D, D–E. Give them the weights 1 to 6, each used once, so that the MST weighs as much as possible. What is that weight?
Idea.
An MST is forced to use some edges. Waste cheap weights on edges it can skip.
- D–E is a bridge, so it is in every spanning tree: give it 6.
- Among A, B, C, D the two cheapest weights, 1 and 2, are always taken: two edges cannot form a cycle.
- Waste weight 3: put 1, 2 and 3 on the triangle A,B,C. Then the edge of weight 3 is skipped.
- D still has to be joined. The cheapest weight left for B–D or C–D is 4.
Answer.
$1+2+4+6=13$.
Common mistake.
Giving the large weights to any edges you like. Only a bridge, or an edge the tree cannot avoid, adds its full weight.
| Statement type | Rule to use | Typical answer |
|---|---|---|
| "must be in the MST" | cut property (distinct weights) | lightest crossing edge |
| "cannot be in the MST" | cycle property | heaviest edge of some cycle |
| "is the MST unique?" | distinct weights ⟹ yes; ties: count choices | multiply choices per tie group |
| "order of vertices in Prim" | cheapest edge leaving the tree each step | grow from the start vertex |
| "MST weight" | Kruskal | sum of $V-1$ taken edges |
| Common mistake | Correction |
|---|---|
| Prim sorts all edges first | that is Kruskal |
| start vertex changes the MST weight | only the order; weight is the same |
| two MSTs can differ in weight | all MSTs have the same weight |
| spanning tree has $V$ edges | $V-1$ edges |
- For "always true" statements, try to break each one with a triangle before accepting it.
- Count the edges you took: stop at exactly $V-1$.
Cut rule adds, cycle rule removes.
8. Disjoint Set Union (union-find)
Each set is a tree of parent pointers. FindSet follows parents to the root; UnionSet makes one root point to the other.
The data structure Kruskal uses to test "are these two vertices already connected?"
The question this lesson answers. How do you know quickly whether two vertices are already connected?
| New word | Meaning |
|---|---|
| representative | the root that names a set |
| path compression | pointing visited nodes straight at the root |
| union by size | hanging the smaller tree under the larger |
Clubs with one captain each. Two people share a club if asking "who is your captain?" gives the same name. Merging clubs changes only one captain's answer.
A disjoint set union keeps vertices in non-overlapping groups. Component[v] stores the parent of $v$; a root has Component[v] == v. Two operations: FindSet(u) returns the root of $u$'s group; UnionSet(u,v) joins the two groups.
Why it works. Each set keeps one representative, so two items are together exactly when their representatives match.
The pseudocode from the PYQ
Component = list(range(n)) # every vertex starts as its own root
def FindSet(u):
if Component[u] == u: # u is a root
return u
return FindSet(Component[u]) # follow the parent upward
def UnionSet(u, v):
x = FindSet(u)
y = FindSet(v)
if x != y: # different groups
Component[y] = x # attach root y under root x
Line 6 follows the parent chain; each recursive call moves one step up the tree. The chain length is the depth of $u$. Line 12 joins two groups by hanging one root under the other.
An example array
| v | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
|---|---|---|---|---|---|---|---|---|
| Component[v] | 0 | 0 | 1 | 2 | 4 | 4 | 6 | 3 |
FindSet(7): follow parents to the root
| call | Component[u] | what happens |
|---|---|---|
| FindSet(7) | 3 | not a root: call on 3 |
| FindSet(3) | 2 | call on 2 |
| FindSet(2) | 1 | call on 1 |
| FindSet(1) | 0 | call on 0 |
| FindSet(0) | 0 | root: return 0 |
Speed-ups (not in the PYQ code). Path compression (set Component[u] to the root while returning) and union by size make operations almost constant time. Without them a long chain makes FindSet $O(n)$.
Worked example: Trace a union
Problem.
Start with 5 singletons. UnionSet(0,1), UnionSet(1,2). Final Component array?
Idea.
Attach the second root under the first.
- UnionSet(0,1): FindSet(0)=0, FindSet(1)=1, so Component[1]=0.
- UnionSet(1,2): FindSet(1)=0, FindSet(2)=2, so Component[2]=0.
Answer.
[0,0,0,3,4]
Common mistake.
Writing Component[1]=2 (wrong direction).
| Common mistake | Correction |
|---|---|
| returning Component[u] instead of the root | follow parents until Component[u]==u |
| stopping after one step | keep following the chain |
| thinking union copies elements | it only changes one parent pointer |
Five unions: parent pointers and the array
Every vertex is its own root: six groups of size one.
FindSet(0) = 0 and FindSet(1) = 1. The roots differ, so the groups must merge.
Root 1 now points to root 0. Only one array entry changed.
FindSet(2) = 2 and FindSet(3) = 3. The roots differ, so the groups must merge.
Root 3 now points to root 2. Only one array entry changed.
FindSet(1) = 0 and FindSet(3) = 2. The roots differ, so the groups must merge.
Root 2 now points to root 0. Only one array entry changed.
FindSet(4) = 4 and FindSet(5) = 5. The roots differ, so the groups must merge.
Root 5 now points to root 4. Only one array entry changed.
FindSet(3) = 0 and FindSet(5) = 4. The roots differ, so the groups must merge.
Root 4 now points to root 0. Only one array entry changed.
Follow parents: 5 → 4 → 0, so the root is 0.
DSU inside Kruskal. For each sorted edge $(u,v)$: if FindSet(u) ≠ FindSet(v) take the edge and UnionSet(u, v); otherwise skip it (cycle).
Worked example: A chain builds up
Problem.
Starting with four single sets, run union(1,2), union(2,3), union(3,4), each time pointing the first root at the second. How many links does FindSet(1) follow?
Idea.
Write the parent of every element.
- 1 points to 2.
- 2 points to 3.
- 3 points to 4.
- From 1 the path is 2, 3, 4.
Answer.
3 links
Common mistake.
Assuming every element points straight at the root.
See the array as a forest. Draw one arrow from every element to its parent. A root has no arrow. For Component = [0, 0, 0, 1, 4, 4] there are two trees, so two sets: {0, 1, 2, 3} with root 0, and {4, 5} with root 4.
Find, flatten, then join
Two trees, rooted at 0 and 4. Each arrow points from a vertex to its parent.
Follow the arrow 3 → 1.
Follow the arrow 1 → 0. Vertex 0 points to itself, so the answer is 0.
On the way back, point 3 straight at the root. The next FindSet(3) takes one step.
Their roots are 0 (size 4) and 4 (size 2). Hang the smaller root under the larger.
One entry changes and the two sets become one tree.
Why hang the small tree under the large one? An element moves one level deeper only when its set is the smaller one, and then its set at least doubles. A set can double only about $\log_2 n$ times before it holds all $n$ elements. So no element ever sits deeper than $\log_2 n$, and FindSet costs $O(\log n)$.
Union-find with both speed-ups
parent = list(range(n))
size = [1] * n
def find(u):
if parent[u] != u:
parent[u] = find(parent[u]) # path compression
return parent[u]
def union(u, v):
x, y = find(u), find(v)
if x == y:
return False # already joined: the edge would close a cycle
if size[x] < size[y]:
x, y = y, x # make x the larger set
parent[y] = x
size[x] += size[y]
return True
The array version, without trees. Another way is to store each vertex's set label directly. FindSet is then one look-up, but a union must rewrite labels. If we keep a list of members for every set and always relabel the smaller set, each vertex is relabelled at most $\log_2 n$ times.
| Version | FindSet | Union | Note |
|---|---|---|---|
| labels, relabel by scanning all vertices | $O(1)$ | $O(n)$ | simplest |
| labels + member lists + smaller into larger | $O(1)$ | $O(\log n)$ on average over many unions | $m$ unions cost $O(m\log m)$ in total |
| parent trees, no balancing | $O(n)$ worst case | two finds, then $O(1)$ | a long chain can form |
| parent trees + union by size | $O(\log n)$ | two finds, then $O(1)$ | height stays logarithmic |
| union by size + path compression | almost constant on average | almost constant on average | what Kruskal uses in practice |
Worked example: Union by size, step by step
Problem.
Five single sets 0 to 4. Run union(0,1), union(2,3), union(0,2), union(4,0) with the code above (on a size tie the first root stays on top). Give the final parent array.
Idea.
Find both roots, then hang the smaller set under the larger.
- union(0,1): sizes 1 and 1, so parent[1] = 0; size of 0 is 2.
- union(2,3): parent[3] = 2; size of 2 is 2.
- union(0,2): sizes 2 and 2, tie, so parent[2] = 0; size of 0 is 4.
- union(4,0): roots 4 (size 1) and 0 (size 4). Swap so 0 is on top: parent[4] = 0.
Answer.
[0, 0, 0, 2, 0]
Common mistake.
Writing parent[3] = 0. Union changes only a root's parent; 3 moves only when a later find compresses its path.
Same root, same set.
| Step | Method for any exam question |
|---|---|
| 1 | Find both roots. |
| 2 | Same root: already joined. |
| 3 | Different: link one root under the other. |
9. Topological sort and longest paths in a DAG
Repeatedly take a task that has nothing left to wait for, and cross it off everyone else’s list.
How to line up tasks so every prerequisite comes first, and how long the longest chain of prerequisites is.
The question this lesson answers. In what order can dependent tasks be done, and how many rounds does the longest chain force?
This is week 4 material that the past papers collected here do not ask about. Try the questions at the end first; if you get them all, move on.
Getting dressed: socks before shoes, shirt before tie. Any order that never breaks a "before" rule is acceptable.
A DAG is a directed acyclic graph. An edge $u\to v$ means "$u$ must come before $v$". A topological order lists all vertices so that every edge points from earlier to later.
Why a DAG always has a starting task. Suppose every vertex had an incoming edge. Walk backwards along incoming edges for ever. With finitely many vertices you must repeat one, which is a cycle. So some vertex has indegree 0. Remove it and what remains is still a DAG, so the same step works again until nothing is left. With a cycle, no vertex on it can ever come first, so no order exists.
(1) Compute every indegree. (2) Queue the vertices with indegree 0. (3) Take one, output it, and lower the indegree of each of its neighbours. (4) Queue any that reach 0. If fewer than $V$ vertices come out, the graph has a cycle.
Starting indegrees: A=2, B=1, C=0, D=3, E=0, F=1. So C and E start in the queue. All longest values start at 0.
One pass: order and longest chain together
| take | indegrees now | queue after | longest raised | order so far |
|---|---|---|---|---|
| C | A→1, D→2 | E | A=1, D=1 | C |
| E | A→0, B→0 | A, B | B=1 | C E |
| A | D→1 | B | D=2 | C E A |
| B | D→0 | D | - | C E A B |
| D | F→0 | F | F=3 | C E A B D |
| F | - | empty | - | C E A B D F |
Topological sort, one edge removal at a time
Vertices with in-degree 0 wait for nothing, so they start in the queue.
Lunder a node is the longest chain ending there.Take C from the front of the queue and place it next in the order.
in-degree[A] drops to 1 and L[A] is now 1.
in-degree[D] drops to 2 and L[D] is now 1.
Take E from the front of the queue and place it next in the order.
in-degree[A] drops to 0 and L[A] is now 1. A joins the queue.
in-degree[B] drops to 0 and L[B] is now 1. B joins the queue.
Take A from the front of the queue and place it next in the order.
in-degree[D] drops to 1 and L[D] is now 2.
Take B from the front of the queue and place it next in the order.
in-degree[D] drops to 0 and L[D] is now 2. D joins the queue.
Take D from the front of the queue and place it next in the order.
in-degree[F] drops to 0 and L[F] is now 3. F joins the queue.
Take F from the front of the queue and place it next in the order.
All vertices came out, so there is no cycle. Order: C, E, A, B, D, F.
Topological order and longest path (in edges)
from collections import deque
def topo_longest(adj):
indeg = {u: 0 for u in adj}
for u in adj:
for v in adj[u]:
indeg[v] += 1
longest = {u: 0 for u in adj}
q = deque(u for u in adj if indeg[u] == 0)
order = []
while q:
u = q.popleft()
order.append(u)
for v in adj[u]:
longest[v] = max(longest[v], longest[u] + 1) # weighted: longest[u] + w
indeg[v] -= 1
if indeg[v] == 0:
q.append(v)
return order, longest # len(order) < len(adj) means there is a cycle
Why one pass is enough. The longest path ending at $v$ comes through one of its predecessors: $L(v)=\max_{u\to v}\,(L(u)+1)$, and $L(v)=0$ if there is none. A vertex leaves the queue only after all its predecessors have left, so each $L(u)$ is already final when it is used.
Worked example: Fewest semesters
Problem.
Using the course graph, any number of courses may be taken in one semester, but only after their prerequisites. What is the fewest number of semesters?
Idea.
A chain of courses must take one semester each.
- The longest values are A=1, B=1, C=0, D=2, E=0, F=3.
- The largest is 3 edges, a chain of 4 courses.
- Taking each course in semester L + 1 meets every rule.
Answer.
4 semesters.
Common mistake.
Answering with the number of edges instead of the number of courses in the chain.
Worked example: Longest is not the BFS level
Problem.
In the same graph there is an edge C→D. Why is L(D) = 2 although D is one edge away from C?
Idea.
Longest path takes the maximum over predecessors; BFS takes the first discovery.
- C→D gives the candidate 0 + 1 = 1.
- A→D gives 1 + 1 = 2 (path C, A, D).
- The maximum is kept.
Answer.
A longer route exists, and every prerequisite must be satisfied.
Common mistake.
Running BFS and calling the level the longest distance.
Cost. Each vertex is queued once and each edge is handled once: $O(V+E)$ with lists, $O(V^2)$ with a matrix. With DFS: in a DAG every edge $u\to v$ has post($u$) > post($v$), so listing vertices by decreasing post number is also a topological order.
Longest path is easy here because there are no cycles. In a general graph, no efficient algorithm for the longest simple path is known.
Take indegree zero; longest = 1 + the largest before it.
| Step | Method for any exam question |
|---|---|
| 1 | Write all indegrees. |
| 2 | Remove any vertex with 0 and update its neighbours. |
| 3 | For longest paths, update the maximum along each removed edge. |