Minimum Spanning Trees & Union-Find
Kruskal, Prim and the cut property, with disjoint sets in near-constant time.
You must wire 30 buildings together with fiber at the least total cost. The complete graph on 30 vertices has spanning trees, far too many to try, yet one greedy rule finds the cheapest: keep taking the cheapest link that does not close a loop. A one-paragraph exchange argument proves it, and a data structure with near-constant cost per operation makes it fast.
What you’ll learn
- Define spanning trees and minimum spanning trees, and prove the cut property and the cycle property with exchange arguments.
- Implement Kruskal's algorithm with union-find in and Prim's algorithm with a binary heap in , and choose between them and the array version of Prim by the density of the graph.
- Implement union-find with union by size and path compression, prove that union by size keeps every tree's height at most , and state the near-constant amortized bound.
- Recognize minimum-spanning-tree problems in disguise (connecting at minimum cost, virtual vertices, bottleneck routes, clustering) and tell them apart from shortest-path trees and Steiner trees.
Spanning trees and the cut property
A spanning tree of a connected undirected graph is a set of edges that connects all vertices without a cycle; it always has exactly edges. When every edge has a weight , a minimum spanning tree (MST) is a spanning tree of least total weight . If is disconnected, the goal becomes a minimum spanning forest, one tree per component.
Brute force is hopeless. The 7-vertex graph in the widget below already has 168 spanning trees, and the complete graph on vertices has of them (Cayley's formula). The algorithms in this lesson rest on one structural fact about cuts.
Let be an MST that contains . If we are done. Otherwise adding to creates exactly one cycle: plus the tree path from back to .
and lie on opposite sides of the cut, so the tree path between them must cross it somewhere: it contains a crossing edge . Since respects the cut, , and since is light,
Swap them. Removing breaks the only cycle, so is a spanning tree, it still contains , and it is no heavier than . So is an MST containing .
All edge weights of a connected graph are distinct. Which edges are guaranteed to be in its minimum spanning tree?
- The heaviest edge incident to each vertex
- The lightest edge incident to each vertex
- No edge is guaranteed; it depends on the whole graph
- The edges of a shortest-path tree from vertex 1
Show the answer
B. The lightest edge incident to each vertex
Take the cut that puts one vertex alone on its side, . Its crossing edges are exactly the edges at , so the lightest of them is the unique light edge of that cut and belongs to every MST.
Kruskal’s algorithm: lightest edges first
Kruskal's algorithm (1956) sorts the edges by weight and scans them from lightest to heaviest, keeping an edge exactly when its two ends lie in different components of the forest built so far. It is a greedy algorithm: each choice is final.
Why it is correct. Suppose Kruskal keeps , and let be the component of the current forest that contains . The cut is respected by . Any edge lighter than that crosses it was examined earlier, when its ends were in different components (components only grow), so it was kept, and then it would lie inside the forest, which no crossing edge does. So is a light edge of the cut, and the cut property says still extends to an MST. By induction, the final edges form an MST.
Run Kruskal by hand on these edges: A–C 1, D–F 2, B–D 3, B–F 4, D–E 5, C–D 6, A–B 7, C–E 8, E–F 9. What is the weight of the minimum spanning tree?
Show the answer
17
Keep A–C 1, D–F 2 and B–D 3; reject B–F 4, because B–D–F already connects B and F; keep D–E 5 and C–D 6, which joins to . That is edges, so the scan can stop: .
Cost. Sorting takes , and since , , so this is . The scan asks times "are and already connected?" and merges two components times. Answering that question fast is the job of the next step's data structure; with it, the scan costs , so sorting dominates. If the edges arrive already sorted, or have small integer weights that counting sort can order, Kruskal runs in near-linear time.
Union-find: are u and v already connected?
Union-find, also called a disjoint-set structure, keeps a partition of the elements under two operations: find(x) returns the representative of 's set, and union(a, b) merges the sets of and . Each set is a tree of parent pointers whose root is the representative. A find walks up to the root; a union finds both roots and links one under the other. Kruskal's question becomes find(u) == find(v).
Linked carelessly, the trees degenerate. If every union puts the current root under a new element, the sets form a path, and a find from its far end walks pointers.
Path compression points every node on a find path straight at the root, so later finds from those nodes take one step. With both heuristics, any sequence of operations on elements takes time (Tarjan, 1975), where is the inverse Ackermann function: for every below a number vastly larger than the roughly atoms of the observable universe. The bound is amortized: one find can still take steps, but the total over any sequence is near-linear.
class DSU:
def __init__(self, n):
self.parent, self.size = list(range(n)), [1] * n
def find(self, x):
while self.parent[x] != x:
self.parent[x] = self.parent[self.parent[x]] # path halving
x = self.parent[x]
return x
def union(self, a, b):
a, b = self.find(a), self.find(b)
if a == b:
return False # already in one set
if self.size[a] < self.size[b]:
a, b = b, a
self.parent[b] = a # smaller tree under the larger
self.size[a] += self.size[b]
return True
def kruskal(n, edges):
"""edges = [(w, u, v), ...] on vertices 0..n-1. Returns (weight, tree)."""
dsu, total, tree = DSU(n), 0, []
for w, u, v in sorted(edges):
if dsu.union(u, v): # joins two components
total += w
tree.append((u, v, w))
return total, tree # fewer than n - 1 edges: disconnectedThe find is iterative, so there is no recursion limit to hit. Path halving points every other node on the path at its grandparent in a single pass; with union by size it has the same amortized bound as full compression (Tarjan & van Leeuwen, 1984). On the widget's graph, kruskal returns weight 25.
Prim’s algorithm: grow one tree
Prim's algorithm (Prim, 1957; found earlier by Jarník, 1930) grows a single tree from a start vertex, each time adding the lightest edge with exactly one end in the tree. Its correctness is the cut property with = the tree's vertices: the tree respects that cut, and the chosen edge is a light edge of it. The implementation is Dijkstra's algorithm with one change: a waiting vertex is keyed by its cheapest edge into the tree, not by a path length.
import heapq
def prim(n, adj, s=0):
"""adj[u] = [(v, w), ...], each edge listed at both ends.
Returns the weight of a minimum spanning tree of s's component."""
in_tree, total = [False] * n, 0
heap = [(0, s)] # (weight of the edge into the tree, vertex)
while heap:
w, u = heapq.heappop(heap)
if in_tree[u]:
continue # stale entry: u joined the tree already
in_tree[u] = True
total += w
for v, wv in adj[u]:
if not in_tree[v]:
heapq.heappush(heap, (wv, v))
return totalLazy deletion, as in Dijkstra's algorithm: an edge is pushed only by whichever end joins the tree first, so the heap receives at most entries and the total is in the worst case. With a Fibonacci heap and decrease-key, Prim runs in (Fredman & Tarjan, 1987).
| Situation | Use | Time |
|---|---|---|
| an edge list, sparse graph ( near ) | Kruskal with union-find | |
| adjacency lists | Prim with a binary heap | |
| a dense graph, or all pairs of points () | Prim with an array of best edge costs and no heap: each step scans the array for the minimum | |
| edges already sorted, or small integer weights | Kruskal, sorting by counting | after sorting |
| parallel or distributed machines | Borůvka's rounds (see the Optimal lessons) | rounds of work |
You must connect points in the plane, and an edge between any two points costs their Euclidean distance (about possible edges). Which approach is the most efficient?
- Kruskal: build the list of all pairs, sort it, and scan
- Prim with a binary heap over all pairs
- Prim with an array of best edge costs, computing distances on the fly
- Dijkstra's algorithm from point 0
Show the answer
C. Prim with an array of best edge costs, computing distances on the fly
The graph is complete, so simple steps with no edge list is the best fit. Kruskal and heap-based Prim are correct, but they pay an extra logarithmic factor on edges (roughly to steps), and Kruskal must also store every pair.
Recognizing it
Signals. "Connect all of them at minimum total cost", "every pair must be able to reach each other, directly or not", "build roads, cables or pipes". Also: "make the heaviest link on the route as light as possible" (bottleneck), "split into groups that are as far apart as possible" (clustering), and "either build a facility here or connect to one that exists" (a virtual vertex). The answer always uses edges, and the constraints usually allow , or when every pair of points is a possible edge.
| Problem (in our words) | Key idea | Time |
|---|---|---|
| Connect points with cable; a cable between two points costs their Manhattan distance | An implicit complete graph: array Prim, computing each distance when needed | |
| Close roads to save maintenance while every city stays reachable; maximize the money saved | Keep an MST and close the rest: saving = total weight − MST weight | |
| Some roads already exist; add the cheapest new roads that connect every city | Union the existing roads first (they cost nothing), then run Kruskal on the candidates | |
| Drive from one city to another so that the heaviest road on the route is as light as possible | The path between them in an MST is a minimum-bottleneck path (proved in the Optimal lessons) | , then per query |
| Split items into groups so that the closest two items in different groups are as far apart as possible | Kruskal stopped when components remain: single-linkage clustering |
Common bugs.
- Not checking that the result has edges: a disconnected input yields a forest, and the "answer" silently ignores some vertices.
- Sorting the edges by their endpoints instead of their weight (put the weight first in each tuple).
- Building Prim's adjacency lists with each undirected edge in one direction only.
- A recursive find on or more elements in Python: the recursion limit. Write it as a loop.
- Overflow in C++: edges of weight up to need a 64-bit total (
long long). - Union-find with neither union by size nor compression: adversarial inputs make each find .
- Assuming the MST is unique when weights tie, or comparing your tree with an expected one edge by edge.
Each of towns needs electricity. Town can build its own generator for , or be joined by a power line to another town for ; a town joined to a town with power has power too. How do you find the cheapest plan?
- Build a generator in the town with the smallest , then take a shortest-path tree from it
- Add a virtual "power plant" vertex joined to each town by an edge of weight , and find an MST of the vertices
- It is a Steiner tree problem, so only an approximation is possible
- Compute a maximum flow from the cheapest generator to every town
Show the answer
B. Add a virtual "power plant" vertex joined to each town by an edge of weight , and find an MST of the vertices
A plan is a set of generators and lines in which every town is connected to some generator. Merge all generators into one virtual vertex: then a plan is exactly a spanning tree of the vertices (redundant lines can be dropped), and its cost is the tree's weight. The MST is the cheapest plan, and it may build several generators.
Key takeaways
- Cut property: the lightest edge across any cut that the chosen edges respect is safe to add. Cycle property: an edge strictly heavier than the rest of some cycle is in no MST. With distinct weights the MST is unique.
- Kruskal sorts the edges and keeps those that join two components: , with union-find answering "already connected?".
- Prim grows one tree, always adding the lightest edge that leaves it: with a binary heap, with an array, which is best for dense graphs.
- Union-find with union by size (or rank) keeps trees at height ; with path compression as well, operations take time, where for any practical .
- Signals: connect everything at minimum total cost, minimize the largest edge used, split into well-separated groups, or add a virtual vertex for "build here or connect". A shortest-path tree and a Steiner tree are different problems.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
All weights are distinct, and the edge is the heaviest edge of some cycle. Can belong to the minimum spanning tree?
- Yes, if is a bridge
- Only if the cycle has an odd number of edges
- No: an MST containing could swap it for a lighter edge of the cycle
- Yes, if is the lightest edge at one of its endpoints
Show the answer
C. No: an MST containing could swap it for a lighter edge of the cycle
Deleting from an MST splits into two sides, and the rest of the cycle must cross between them with an edge lighter than . Then is a lighter spanning tree, a contradiction. This is the cycle property.
On a connected graph with distinct weights, Kruskal's and Prim's algorithms...
- build the same tree, possibly adding its edges in different orders
- build different trees of the same total weight
- add the same edges in the same order, from lightest to heaviest
- agree only when the graph is dense
Show the answer
A. build the same tree, possibly adding its edges in different orders
With distinct weights the MST is unique, so both must return it. The order differs: Kruskal adds edges by increasing weight, while Prim only considers edges leaving its tree, so on the widget's graph it adds C–D 5 before D–E 2.
Union-find uses union by size but no path compression, on elements. In the worst case, how many parent pointers can a single find follow?
- 1023
- 32
- 10
- 1
Show the answer
C. 10
A tree of height built by union by size has at least elements, so . Pairing elements, then pairs of pairs, and so on, reaches exactly height 10.
You must delete edges from a connected weighted graph until it is a tree, keeping the total weight of the remaining edges as large as possible. What works?
- Nothing greedy works; it needs dynamic programming
- Kruskal's algorithm scanning the edges from heaviest to lightest
- Dijkstra's algorithm from the heaviest edge
- Kruskal's algorithm as usual, then keep the edges it rejected
Show the answer
B. Kruskal's algorithm scanning the edges from heaviest to lightest
A maximum spanning tree is a minimum spanning tree for the weights , and negating weights just reverses the scan order. The cut and cycle properties hold with "heaviest" in place of "lightest".
Go deeper
- Union-Find & the Inverse Ackermann Function · Path compression, union by rank and Tarjan’s analysis.
- MST Algorithms: Borůvka to Linear Time · The cut and cycle properties, Borůvka, and randomized linear time.
- MST Variants & Applications · Bottleneck paths, second-best trees, Kruskal reconstruction trees and clustering.
Further reading
- J. B. Kruskal, "On the shortest spanning subtree of a graph and the traveling salesman problem," Proceedings of the American Mathematical Society 7(1) (1956), 48–50.
- R. C. Prim, "Shortest connection networks and some generalizations," Bell System Technical Journal 36(6) (1957), 1389–1401.
- R. E. Tarjan, "Efficiency of a good but not linear set union algorithm," Journal of the ACM 22(2) (1975), 215–225.
- T. H. Cormen, C. E. Leiserson, R. L. Rivest & C. Stein, Introduction to Algorithms, 4th ed. (MIT Press, 2022), chapters 19 and 21.