21. Minimum Spanning Trees
Connect everything at the lowest total cost
You're a telecommunications company laying fiber-optic cable between cities. Every possible route has a cost — distance, terrain difficulty, permits. You need to connect all cities into a single network, but you want to minimize the total cable laid. You don't need every possible connection, just enough to reach everywhere.
This is the minimum spanning tree problem: given a connected, weighted, undirected graph, find a subset of edges that connects all vertices with the smallest possible total weight — and forms no cycles.
The Problem
Given a connected, weighted, undirected graph with V vertices and E edges, find a spanning tree — a subset of exactly V-1 edges that connects all vertices — whose total edge weight is minimized.
What makes it a tree?
A spanning tree of a graph with V vertices has exactly V-1 edges, connects all vertices, and contains no cycles. Adding any edge would create a cycle; removing any edge would disconnect the graph.
A Simple Example
A 6-vertex weighted graph
2 3
A ------ B ------ C
| \ | / |
6 | 8\ 5 | /7 | 9
| \ | / |
D ------ E ------ F
4 1
Which edges should we keep to connect all six vertices at minimum total cost?
There are two classic algorithms that solve this, each with a beautifully different strategy.
Kruskal's Algorithm: Sort and Greedily Add
Kruskal's algorithm takes a global view: sort all edges by weight, then greedily add the cheapest edge that doesn't create a cycle. It uses Union-Find to track connected components efficiently.
-
Sort all edges by weight
Cheapest edges first.
-
Initialize Union-Find
MakeSet for every vertex — each starts in its own component.
-
Process edges in order
For each edge (u, v, w): if
Find(u) != Find(v), add the edge to the MST and callUnion(u, v). Otherwise, skip it — it would create a cycle. -
Stop when you have V-1 edges
That's a spanning tree — all vertices are connected.
Kruskal's Worked Example
Step-by-step execution
Edges sorted by weight:
(E,F,1) (A,B,2) (A,C,3) (D,E,4) (B,E,5)
(A,D,6) (C,E,7) (A,E,8) (C,F,9)
Step 1: Add (E,F,1) — Find(E)!=Find(F), union them. MST: {E-F} cost: 1
Step 2: Add (A,B,2) — Find(A)!=Find(B), union them. MST: {E-F, A-B} cost: 3
Step 3: Add (A,C,3) — Find(A)!=Find(C), union them. MST: + A-C cost: 6
Step 4: Add (D,E,4) — Find(D)!=Find(E), union them. MST: + D-E cost: 10
Step 5: Add (B,E,5) — Find(B)!=Find(E), union them. MST: + B-E cost: 15
Step 6: Skip (A,D,6) — Find(A)==Find(D), would create cycle!
Step 7: Skip (C,E,7) — Find(C)==Find(E), would create cycle!
Step 8: Skip (A,E,8) — Find(A)==Find(E), would create cycle!
Step 9: Skip (C,F,9) — Find(C)==Find(F), would create cycle!
Done — 5 edges for 6 vertices.
Total MST weight: 15
Why Kruskal's Works: The Cut Property
The Cut Property
For any cut of the graph (a partition of vertices into two non-empty sets), the minimum-weight edge crossing the cut must be in every MST. When Kruskal's adds the cheapest edge connecting two components, that edge is the minimum-weight edge crossing the cut between those components. So it's safe to include it.
Kruskal's Pseudocode
function kruskal(vertices, edges):
mst = []
sort edges by weight (ascending)
// Initialize Union-Find
for each vertex v:
MakeSet(v)
for each edge (u, v, w) in sorted order:
if Find(u) != Find(v):
mst.append((u, v, w))
Union(u, v)
if mst.length == |vertices| - 1:
break
return mst
Kruskal's Complexity
| Aspect | Value |
|---|---|
| Sorting edges | O(E log E) |
| Union-Find operations | O(E · α(V)) ≈ O(E) |
| Total | O(E log E) |
| Space | O(V + E) |
The sorting step dominates. Since E ≤ V², we have log E ≤ 2 log V, so O(E log E) = O(E log V).
Prim's Algorithm: Grow a Single Tree
Prim's algorithm takes a local view: start from any vertex and repeatedly add the cheapest edge that connects the growing tree to a vertex not yet in the tree. It's structurally similar to Dijkstra's algorithm — both use a priority queue to greedily expand outward.
-
Start from any vertex
Add it to the tree. Insert all its edges into a priority queue.
-
Extract the minimum-weight edge
Pull the cheapest edge from the priority queue. If it leads to a vertex already in the tree, discard it. Otherwise, add the edge to the MST and mark the new vertex as part of the tree.
-
Add the new vertex's edges
Insert all edges from the newly added vertex into the priority queue (only edges leading to vertices not yet in the tree matter).
-
Repeat until all vertices are in the tree
After V-1 edges, we have a spanning tree.
Prim's Worked Example
Starting from vertex A
Tree = {A}, PQ = [(A-B,2), (A-C,3), (A-D,6), (A-E,8)]
Step 1: Extract (A-B,2). B not in tree. Add edge.
Tree = {A,B}, MST cost: 2
Add B's edges: (B-E,5), (B-C,3 — but A-C already in PQ with same cost)
Step 2: Extract (A-C,3). C not in tree. Add edge.
Tree = {A,B,C}, MST cost: 5
Add C's edges: (C-E,7), (C-F,9)
Step 3: Extract (B-E,5). E not in tree. Add edge.
Tree = {A,B,C,E}, MST cost: 10
Add E's edges: (E-D,4), (E-F,1)
Step 4: Extract (E-F,1). F not in tree. Add edge.
Tree = {A,B,C,E,F}, MST cost: 11
Step 5: Extract (E-D,4). D not in tree. Add edge.
Tree = {A,B,C,D,E,F}, MST cost: 15
Done — all vertices in tree. Total MST weight: 15
Both algorithms find the same total weight (15), though the specific tree may differ if there are ties.
Prim's Pseudocode
function prim(graph, start):
inTree = {}
mst = []
pq = new MinPriorityQueue()
inTree[start] = true
for each edge (start, v, w):
pq.insert((start, v, w), w)
while pq is not empty and mst.length < |vertices| - 1:
(u, v, w) = pq.extractMin()
if inTree[v]: continue
inTree[v] = true
mst.append((u, v, w))
for each edge (v, x, w2) where not inTree[x]:
pq.insert((v, x, w2), w2)
return mst
Prim's Complexity
| Priority Queue | Insert | Extract-Min | Total |
|---|---|---|---|
| Binary heap | O(log E) | O(log E) | O(E log V) |
| Fibonacci heap | O(1) amortized | O(log V) amortized | O(E + V log V) |
Kruskal vs. Prim
| Property | Kruskal | Prim |
|---|---|---|
| Strategy | Sort all edges, add cheapest non-cycle edge | Grow tree from a start vertex, add cheapest outgoing edge |
| Data structure | Union-Find | Priority queue |
| Complexity | O(E log E) | O(E log V) with binary heap |
| Best for | Sparse graphs (E ≈ V) | Dense graphs (E ≈ V²) |
| Parallelizable? | Yes (Borůvka variant) | Sequential by nature |
| Needs sorted edges? | Yes | No |
For sparse graphs, Kruskal is usually faster and simpler to implement. For dense graphs, Prim with a Fibonacci heap wins asymptotically. In practice, Kruskal with a good Union-Find is the most common choice.
Uniqueness of the MST
A graph has a unique MST if and only if every edge weight is distinct. When there are ties (multiple edges with the same weight), there may be multiple valid MSTs — all with the same total weight, but using different edges.
Multiple MSTs from tied edges
1 1
A ----- B ----- C
\ /
\ 1 /
+--- D ---+
All three edges have weight 1.
Any two of them form a valid MST with total weight 2.
There are three distinct MSTs.
Borůvka's Algorithm: The Parallel Approach
There's a third MST algorithm worth knowing — Borůvka's (1926), the oldest of the three. It works in rounds: in each round, every component simultaneously picks its cheapest outgoing edge. All those edges are added, merging components. The number of components halves each round, so the algorithm finishes in O(log V) rounds.
This inherent parallelism makes Borůvka's algorithm the foundation of many parallel and distributed MST implementations.
Where MSTs Are Used
| Application | How it uses MSTs |
|---|---|
| Network design | Lay cable, pipe, or wire connecting all locations at minimum total cost |
| Cluster analysis | Remove the longest edges from an MST to partition data into clusters |
| Approximation algorithms | MSTs provide 2-approximations for the Traveling Salesman Problem on metric graphs |
| Image segmentation | Felzenszwalb's algorithm uses MST-based component merging to segment images |
| Circuit design | Connect pins on a chip with minimum total wire length |
| Taxonomy | Build phylogenetic trees connecting species by minimum genetic distance |
Key Takeaways
- A minimum spanning tree connects all vertices with V-1 edges at the lowest total weight, with no cycles
- Kruskal's: sort edges by weight, greedily add the cheapest edge that doesn't create a cycle (using Union-Find) — O(E log E)
- Prim's: grow a tree from one vertex, always adding the cheapest edge to a new vertex (using a priority queue) — O(E log V)
- Both are correct because of the cut property: the lightest edge crossing any cut must be in the MST
- Kruskal is simpler and better for sparse graphs; Prim is better for dense graphs
- MSTs are unique when all edge weights are distinct
- Borůvka's algorithm enables parallel MST computation by having all components simultaneously pick their cheapest outgoing edge
Try It Yourself — Minimum Spanning Tree
Generate a random graph or place your own nodes, then watch Kruskal's or Prim's algorithm build the MST step by step. Edges being considered are highlighted, accepted edges turn green, and rejected edges flash red.
Minimum spanning trees are one of the cleanest examples of greedy algorithms in action — and a case where the greedy choice is provably optimal. Kruskal's "sort and merge" and Prim's "grow outward" are two sides of the same coin, both justified by the cut property. If you've already read the Union-Find article, you've seen the data structure that makes Kruskal's practical. And if you've read Dijkstra, you've already seen Prim's core loop in a different disguise — same priority queue expansion, different invariant.