Sub topic 12
Minimum Spanning Trees with Kruskal and Prim
This chapter assumes you can read Python with heaps (heapq), know adjacency lists and weighted undirected graphs, and have seen the exchange argument from the earlier chapter on proof techniques. You will use that argument again here to prove the cut property. Both Kruskal's algorithm and Prim's algorithm depend on that property.
The Problem
A spanning tree of a connected, undirected graph with V vertices is a set of V − 1 edges that connects every vertex and contains no cycle. A minimum spanning tree (MST) is a spanning tree whose total edge weight is as small as possible. Typical uses are laying cable or pipe between sites at the lowest total cost, clustering points by deleting the heaviest MST edges, and producing lower bounds for routing problems such as the travelling salesman problem.
A graph can have exponentially many spanning trees, so checking them all is out of the question. Both MST algorithms in this chapter are greedy. They add one edge at a time and never remove an edge once it is in the tree. They differ only in which edge they consider next.
The Cut Property
A cut splits the vertices into two non-empty groups, S and V − S. An edge crosses the cut if one endpoint is in S and the other is in V − S.
Cut property. Take any cut, and let e be a minimum-weight edge crossing it. Then some MST contains e. If e is the only lightest crossing edge, every MST contains it.
Proof by exchange. Let T be an MST that does not contain e = (u, v). Adding e to T creates exactly one cycle. That cycle starts in S at u, crosses to v in V − S, and has to return to S, so it uses at least one other crossing edge f. Swapping them gives T' = T + e − f, which is still a spanning tree: it has V − 1 edges and stays connected because the cycle offers another route. Since w(e) ≤ w(f), we get w(T') ≤ w(T). So T' is also an MST, and it contains e. If e is strictly lighter than every other crossing edge, then w(T') < w(T), which contradicts T being minimal. In that case every MST must contain e.
The matching rule for excluding edges is the cycle property. If e is the unique heaviest edge on some cycle, then no MST contains e.
Every correct MST algorithm amounts to a rule for picking cuts so that each edge it adds is the lightest edge crossing some cut.
Kruskal's Algorithm
Kruskal's algorithm sorts all edges by weight. It then scans them from lightest to heaviest and adds each edge that does not form a cycle with the edges already chosen.
Here is why this follows the cut property. Suppose Kruskal adds edge (u, v). At that moment u and v are in different components of the forest built so far. Let S be u's component. No lighter edge crosses this cut, because every lighter edge has already been examined and was either added or rejected for joining two vertices that were already connected. So (u, v) is a lightest edge crossing the cut.
To test "does this edge form a cycle?" quickly, Kruskal uses a union-find (disjoint-set) structure. find(x) returns a representative for x's component. Two vertices are already connected exactly when their representatives are equal.
def kruskal(n, edges):
parent = list(range(n))
def find(x):
while parent[x] != x:
parent[x] = parent[parent[x]]
x = parent[x]
return x
mst = []
for w, u, v in sorted(edges):
ru, rv = find(u), find(v)
if ru != rv:
parent[ru] = rv
mst.append((u, v, w))
return mst
edges = [(1, 0, 1), (4, 0, 2), (2, 1, 2), (6, 1, 3), (3, 2, 3)]
print(kruskal(4, edges)) # [(0, 1, 1), (1, 2, 2), (2, 3, 3)]Edges are stored as (w, u, v) so that sorted orders them by weight first. The line parent[x] = parent[parent[x]] is path halving: each lookup shortens the path it walks, which keeps later lookups fast. Production code usually adds union by rank, which attaches the shorter tree under the taller one. With both techniques, each union-find operation costs nearly constant amortized time. The sort then dominates, so the total cost is O(E log E), which equals O(E log V) because E ≤ V².
Here is the example step by step. Edge 0–1 (weight 1) is added. Edge 1–2 (weight 2) is added. Edge 2–3 (weight 3) is added. Edge 0–2 (weight 4) is skipped because 0 and 2 are already connected. Edge 1–3 (weight 6) is skipped for the same reason. The total weight is 6.
Prim's Algorithm
Prim's algorithm grows a single tree from a start vertex. At each step it adds the cheapest edge that leaves the tree. The cut is always "tree versus everything else," so each edge it adds follows the cut property directly.
import heapq
def prim(n, edges, start=0):
adj = [[] for _ in range(n)]
for w, u, v in edges:
adj[u].append((w, v))
adj[v].append((w, u))
in_tree = [False] * n
heap = [(0, start, -1)] # (weight, vertex, parent)
mst, total = [], 0
while heap:
w, v, p = heapq.heappop(heap)
if in_tree[v]:
continue
in_tree[v] = True
if p != -1:
mst.append((p, v, w))
total += w
for nw, x in adj[v]:
if not in_tree[x]:
heapq.heappush(heap, (nw, x, v))
return mst, total
edges = [(1, 0, 1), (4, 0, 2), (2, 1, 2), (6, 1, 3), (3, 2, 3)]
print(prim(4, edges)) # ([(0, 1, 1), (1, 2, 2), (2, 3, 3)], 6)This is the lazy version. The heap can hold outdated entries for vertices that have already joined the tree, and the if in_tree[v]: continue check discards them when they are popped. The heap holds at most E entries, so the running time is O(E log V).
An eager version keeps only one entry per vertex and lowers its key when a cheaper edge appears. That needs an indexed heap, which heapq does not provide. For dense graphs, where E is close to V², a plain array of "best edge into each vertex" with a linear scan for the minimum runs in O(V²). That beats both heap versions on dense graphs.
Choosing Between Them
| Factor | Kruskal | Prim (binary heap) | Prim (array) |
|---|---|---|---|
| Time | O(E log E) | O(E log V) | O(V²) |
| Best fit | Sparse graphs, edge lists | Sparse or medium graphs, adjacency lists | Dense graphs |
| Main data structure | Sorting plus union-find | Priority queue | Array of best distances |
| Disconnected input | Returns a minimum spanning forest | Covers only the start vertex's component | Same as heap version |
| Edges already sorted | Near-linear time | No benefit | No benefit |
Kruskal also suits clustering. If you stop it once k components remain, you get the k-clustering with the largest possible minimum distance between clusters.
Edge Cases and Common Errors
- Disconnected graphs. A disconnected graph has no spanning tree. Check
len(mst) == n - 1before treating the result as an MST. - Undirected edges stored in one direction only. Prim's adjacency list needs every edge in both directions. If you add only one, the algorithm silently misses edges.
- Directed graphs. The MST of a directed graph is a different problem, the minimum arborescence, solved by the Chu–Liu/Edmonds algorithm. Running Prim or Kruskal on a directed graph gives wrong answers.
- Negative and equal weights. Negative weights are fine. The cut property only compares weights, so adding a constant to every edge does not change which tree is minimal. With equal weights there can be several MSTs, and the two algorithms may return different ones with the same total weight. If all weights are distinct, the MST is unique.
- Heap tie-breaking. If the heap tuples contain objects that cannot be compared, such as dictionaries or custom nodes, a tie on weight raises
TypeError. Put a counter in the tuple, as in the Huffman chapter, or use integer vertex IDs as here. - Confusing MSTs with shortest paths. An MST minimizes total edge weight. It does not minimize the distance from one vertex to the others. Prim's code looks like Dijkstra's, but Prim's heap key is the weight of a single edge, while Dijkstra's key is the total distance from the source.
Exercise
A graph has vertices A, B, C, D and edges A–B 5, A–C 1, B–C 4, B–D 2, C–D 6. Without running any algorithm, use the cut and cycle properties to decide whether edges B–C and C–D are in the MST. Then give the MST and its weight.
Show answer
The cycle B–C–D has edges B–C 4, B–D 2 and C–D 6. C–D is the unique heaviest edge on that cycle, so the cycle property excludes it. For the cut {A, C} versus {B, D}, the crossing edges are A–B 5, B–C 4 and C–D 6. B–C is the unique lightest of them, so the cut property puts it in every MST. A–C (1) is the unique lightest edge touching A, and B–D (2) is the unique lightest edge touching D, so both are included as well. The MST is {A–C, B–C, B–D} with weight 1 + 4 + 2 = 7.
Exercise
Give a three-vertex graph where the shortest-path tree from a source differs from the MST, and compare the two totals.
Show answer
Use edges A–B 2, A–C 2, B–C 1, with source A. Dijkstra's shortest-path tree uses A–B and A–C, because each reaches its endpoint at distance 2. Its total weight is 4. The MST uses B–C plus one of the A edges, for a total weight of 3. The MST is lighter overall, but in the MST one of B or C is at distance 3 from A instead of 2.
Exercise
Modify kruskal so that it raises ValueError when the input graph is disconnected, and explain why the check is correct.
Show answer
After the loop, add if len(mst) != n - 1: raise ValueError("graph is disconnected"). Kruskal adds an edge only when it joins two different components, so each added edge reduces the number of components by one. It begins with n components. It ends with one component, meaning it has added n − 1 edges, exactly when the graph is connected.