A spanning tree of a connected, undirected graph is a subset of edges that connects all V vertices with no cycles, which always means exactly V - 1 edges. A minimum spanning tree (MST) is a spanning tree with the smallest possible total weight. Two greedy algorithms find one: Kruskal's (sort the edges, add each one that does not create a cycle) and Prim's (grow a single tree from a start vertex). Both run in O(E log V) and power network design, clustering and approximation algorithms.
Think of it like
Paving roads between villages
A county wants every village reachable from every other over paved roads, and pays per mile of paving. It does not need to pave every dirt road: any loop means one road in it is redundant. The cheapest plan that keeps everyone connected is the minimum spanning tree. Kruskal's crew paves the cheapest remaining road anywhere unless it would close a loop; Prim's crew starts at the county seat and always paves the cheapest road leading to a village not yet connected.
Definitions
- Spanning tree
- A connected, acyclic subgraph containing every vertex. It has exactly
V - 1edges; adding any other edge creates exactly one cycle. - Minimum spanning tree
- A spanning tree whose total edge weight is as small as possible. A graph can have several MSTs with the same total weight.
- Minimum spanning forest
- For a disconnected graph: one MST per connected component.
- Cut
- A partition of the vertices into two non-empty sets
SandV \ S. An edge crosses the cut if its endpoints are on different sides. - Light edge
- A crossing edge of minimum weight for a given cut.
Two properties that make greedy work
Cut property
- For any cut, a lightest edge crossing it belongs to some MST
- If it is strictly the lightest, it belongs to every MST
- Justifies adding edges
- Kruskal and Prim both follow from it
Cycle property
- For any cycle, a strictly heaviest edge on it is in no MST
- Justifies discarding edges
- Explains why Kruskal may skip an edge forever
- Basis of the reverse-delete algorithm
Why the cut property holds (exchange argument). Take an MST T that does not contain the light edge e = (u, v) of some cut. T still connects u and v, so its path between them must cross the cut on some edge f. Swap them: T - f + e is still a spanning tree, and since w(e) ≤ w(f) it is no heavier. So some MST contains e.
Kruskal's algorithm
- 1
Sort the edges
Order all edges by weight, lightest first.
- 2
Start with a forest
Every vertex is its own component, tracked with a Union-Find (Disjoint Set) structure.
- 3
Scan the edges
For edge
(u, v, w): iffind(u) ≠ find(v), the edge joins two different components. Add it to the tree andunionthem. - 4
Skip cycle-forming edges
If
find(u) = find(v), the endpoints are already connected and the edge would close a cycle. Skip it. - 5
Stop at V - 1 edges
The tree is complete. If you run out of edges first, the graph is disconnected.
Example: vertices A..E with edges A-C 1, B-C 2, D-E 2, A-B 4, B-D 5, C-D 8, C-E 10 (already sorted). The visualization above runs Kruskal and Prim on preset graphs.
| Edge | Weight | Action | Components after |
|---|---|---|---|
| A-C | 1 | add | {A, C} {B} {D} {E} |
| B-C | 2 | add | {A, B, C} {D} {E} |
| D-E | 2 | add | {A, B, C} {D, E} |
| A-B | 4 | skip: A and B are already connected (would close A-B-C) | unchanged |
| B-D | 5 | add: 4 = V - 1 edges, done | {A, B, C, D, E} |
| C-D, C-E | 8, 10 | never examined |
Prim's algorithm
Prim's algorithm grows one tree. A priority queue holds edges leaving the tree, keyed by edge weight. Repeatedly pop the lightest; if its far endpoint is already in the tree, the entry is stale and is skipped, otherwise the vertex joins the tree and pushes its own outgoing edges.
| Tree | Candidate edges leaving the tree | Pick |
|---|---|---|
| {A} | A-C 1, A-B 4 | A-C 1 |
| {A, C} | C-B 2, A-B 4, C-D 8, C-E 10 | C-B 2 |
| {A, B, C} | B-D 5, C-D 8, C-E 10 (A-B is now internal) | B-D 5 |
| {A, B, C, D} | D-E 2, C-E 10 | D-E 2 |
Complexity and when each wins
| Algorithm | Time | Best when |
|---|---|---|
| Kruskal (sort + union-find) | O(E log E) = O(E log V) | Sparse graphs, edges given as a list, or edges already sorted |
| Prim, binary heap | O(E log V) | Graphs stored as adjacency lists |
| Prim, array (no heap) | O(V²) | Dense or complete graphs, e.g. all pairs of points |
| Prim, Fibonacci heap | O(E + V log V) | Theory; rarely used in practice |
| Borůvka | O(E log V) | Parallel and distributed settings |
Uniqueness and edge cases
- If all edge weights are distinct, the MST is unique.
- With ties there may be several MSTs, but they all have the same total weight and even the same multiset of edge weights.
- A disconnected graph has no spanning tree. Kruskal naturally produces a minimum spanning forest; detect the situation when fewer than
V - 1edges were added. - Negative weights are fine: both algorithms only compare weights, so adding a constant to every edge does not change which tree is minimal (every spanning tree has exactly
V - 1edges). - Self-loops never belong to a spanning tree, and only the lightest of several parallel edges can matter.
Variants
- Maximum spanning tree: sort in decreasing order (or negate the weights). The path between two vertices in a maximum spanning tree maximizes the smallest edge on the path, which answers "widest path" or maximum-capacity questions.
- Minimax paths: every MST is a minimum bottleneck spanning tree, and the MST path between
uandvminimizes the largest edge on anyu-vpath. Path With Minimum Effort and Swim in Rising Water can be solved with Kruskal-style union-find. - Forced or forbidden edges: union the forced edges first, or skip the forbidden ones, then run Kruskal. This is how you classify critical and pseudo-critical edges.
- Offline threshold queries: sort queries by limit and add edges up to each limit with union-find (Checking Existence of Edge Length Limited Paths).
- Steiner tree: connecting only a subset of required vertices at minimum cost is NP-hard; MST gives a 2-approximation.
Applications
- Network design: laying cable, fiber, pipelines or power lines to connect sites at minimum cost.
- Single-linkage clustering: run Kruskal until
kcomponents remain (equivalently, delete thek - 1heaviest MST edges). This maximizes the minimum distance between clusters. - Approximation algorithms: a preorder walk of the MST gives a tour at most twice the optimal for metric TSP.
- Image segmentation: graph-based methods (Felzenszwalb-Huttenlocher) merge pixel regions in Kruskal order.
- Broadcast in networks: a spanning tree delivers a message to every node without loops.
Complexity
| Algorithm | Time | Space | Notes |
|---|---|---|---|
| Kruskal (sort + union-find) | O(E log E) | O(V + E) | Sorting dominates; DSU operations are nearly O(1) |
| Prim, binary heap (lazy) | O(E log V) | O(V + E) | Heap may hold up to E entries |
| Prim, array | O(V²) | O(V) | Best for dense and complete graphs |
| Prim, Fibonacci heap | O(E + V log V) | O(V + E) | Mostly theoretical |
O(E log E) and O(E log V) are equivalent because E ≤ V².
Implementation
Edges are `(u, v, w)` triples. Returns the MST weight, or -1 if the graph is disconnected. On the example (A to E as 0 to 4) it returns 10.
def kruskal(n: int, edges: list[tuple[int, int, int]]) -> int:
parent = list(range(n))
size = [1] * n
def find(x: int) -> int:
while parent[x] != x:
parent[x] = parent[parent[x]] # path halving
x = parent[x]
return x
total = used = 0
for u, v, w in sorted(edges, key=lambda e: e[2]): # lightest first
ru, rv = find(u), find(v)
if ru == rv:
continue # already connected: would close a cycle
if size[ru] < size[rv]:
ru, rv = rv, ru
parent[rv] = ru # union by size
size[ru] += size[rv]
total += w
used += 1
if used == n - 1:
break # spanning tree complete
return total if used == n - 1 else -1 # -1: graph is disconnected
edges = [(0, 2, 1), (1, 2, 2), (3, 4, 2), (0, 1, 4), (1, 3, 5), (2, 3, 8), (2, 4, 10)]
print(kruskal(5, edges)) # 10Key takeaways
- An MST connects all
Vvertices withV - 1edges at minimum total weight; it is defined for undirected graphs. - The cut property (lightest crossing edge is safe) and the cycle property (heaviest cycle edge is useless) justify greedy algorithms.
- Kruskal sorts edges and uses union-find to skip cycle-forming edges:
O(E log E). - Prim grows one tree with a priority queue keyed by single edge weights:
O(E log V), orO(V²)without a heap for dense graphs. - Distinct weights mean a unique MST; MSTs also solve minimax-path and single-linkage clustering problems.
Common pitfalls
- Using
dist[u] + was Prim's key, which turns it into Dijkstra and returns a shortest-path tree instead of an MST. - Forgetting to check that
V - 1edges were added, and returning a forest's weight for a disconnected graph. - Running Kruskal without path compression or union by size, so
finddegrades toO(V). - Materializing all
O(V²)edges of a complete graph when theO(V²)Prim needs none of them. - Applying MST algorithms to directed graphs.
Interview tips
- State the cut property informally ("the cheapest edge leaving any group of vertices is always safe to take") to justify the greedy choice.
- Pick Kruskal when edges come as a list and Prim when you have adjacency lists or a complete graph; say why.
- Be ready to implement union-find with path compression and union by size from scratch in a few lines.
Real-world applications
- Designing telecommunication, electrical, water and road networks at minimum cost.
- Single-linkage hierarchical clustering and taxonomy construction.
- 2-approximation for the metric traveling salesman problem.
- Graph-based image segmentation.
- Loop-free broadcast trees in networks (spanning tree protocols).
Practice problems
Test yourself
How many edges does a spanning tree of a connected graph with V vertices have?
Related topics
Finished this lesson? Track it to see your progress on the roadmap.