Sub topic 7
Disjoint Sets: Union by Rank and Path Compression
Kruskal's algorithm looks at edges one at a time and has to answer one question for each: are these two endpoints already connected by edges I have kept? A full graph search for every edge would make the algorithm quadratic. A disjoint-set structure (also called union-find) answers that question in time that is effectively constant. This chapter builds that structure, explains the two optimizations that make it fast, and covers the mistakes people usually make when implementing it.
This chapter assumes you know Big-O notation, Python classes and lists, and what a tree with parent pointers looks like. You do not need Kruskal's algorithm yet. The next chapter uses this structure without explaining it again.
The Problem Disjoint Sets Solve
A disjoint-set structure keeps track of a partition of the elements 0..n-1. A partition splits the elements into groups that do not overlap, and every element belongs to exactly one group. The structure supports two operations:
find(x)returns a representative of the group containingx. Two elements are in the same group exactly whenfindreturns the same representative for both.union(a, b)merges the group containingawith the group containingb.
You cannot split a group once it is merged. That limit is why the structure can be so fast. In Kruskal's algorithm the elements are vertices, each group is a connected component of the edges chosen so far, and union runs whenever an edge joins two components.
Representing Sets as a Forest
Each group is stored as a rooted tree. Every element keeps a pointer to its parent, and the root points to itself. The root is the group's representative.
find(x)follows parent pointers fromxuntil it reaches a node that is its own parent.union(a, b)finds both roots and makes one root the child of the other.
With one parent list and no other rules, this is already correct. The cost of find is the depth of x in its tree, and nothing so far keeps the trees shallow. If you union 0 into 1, then 1 into 2, then 2 into 3, and so on, you get a chain of length n. Each find on the bottom element then costs O(n), so m operations can take O(mn) total.
Two independent fixes solve this. Union by rank limits how deep trees can get when you merge them. Path compression flattens trees whenever you search them.
Union by Rank
The rule is to attach the shorter tree under the root of the taller one. Each root stores a rank, which is an upper bound on the height of its tree.
- A new single-element set has rank 0.
- When you union two roots of different ranks, the lower-rank root becomes a child of the higher-rank root. No rank changes, because the taller tree does not get any taller.
- When the ranks are equal, pick either root as the new parent and increase its rank by 1.
Induction gives the key fact: a root of rank r has at least 2^r elements in its tree. A rank-0 tree has one element. A root reaches rank r + 1 only by merging two rank-r trees, each of which has at least 2^r elements. Since no tree can hold more than n elements, ranks never go above log2 n. Without any other optimization, every find is O(log n).
Union by size works the same way: store each tree's element count and attach the smaller tree under the larger one. It gives the same O(log n) bound. Size is more useful when you need component sizes later, for example in clustering.
Path Compression
Every find walks a path from a node up to the root. Path compression rewires the nodes on that path so the next lookup is shorter. There are three common variants.
Full compression points every node on the path directly at the root:
def find(self, x):
if self.parent[x] != x:
self.parent[x] = self.find(self.parent[x])
return self.parent[x]Path halving points every other visited node at its grandparent. It takes one pass, needs no recursion, and has the same asymptotic bound. The implementation below uses it.
Path splitting points every visited node at its grandparent. Like halving, it uses a single pass.
Path compression never changes ranks. Once compression has run, a rank can overstate a tree's real height. That is fine, because the union-by-rank proof only needs rank to be an upper bound, and it still is.
The Implementation
The class below combines union by rank with path halving. Its union returns False when the two elements already share a root. In Kruskal's algorithm, that return value is the signal that an edge would close a cycle.
class DisjointSet:
def __init__(self, n):
self.parent = list(range(n))
self.rank = [0] * n
def find(self, x):
# Path halving: point each visited node at its grandparent.
while self.parent[x] != x:
self.parent[x] = self.parent[self.parent[x]]
x = self.parent[x]
return x
def union(self, a, b):
ra, rb = self.find(a), self.find(b)
if ra == rb:
return False # already in the same set; edge would form a cycle
if self.rank[ra] < self.rank[rb]:
ra, rb = rb, ra
self.parent[rb] = ra
if self.rank[ra] == self.rank[rb]:
self.rank[ra] += 1
return True
ds = DisjointSet(6)
print(ds.union(0, 1)) # True
print(ds.union(2, 3)) # True
print(ds.union(0, 2)) # True
print(ds.union(4, 5)) # True
print(ds.parent) # [0, 0, 0, 2, 4, 4]
print(ds.union(3, 1)) # False: 3 and 1 already share root 0
print(ds.parent) # [0, 0, 0, 0, 4, 4]
print(ds.rank) # [2, 0, 1, 0, 1, 0]Tracing the Example
union(0, 1): both roots have rank 0. Node 1 goes under 0, andrank[0]becomes 1.union(2, 3): the same thing happens. Node 3 goes under 2, andrank[2]becomes 1.union(0, 2): both roots have rank 1. Node 2 goes under 0, andrank[0]becomes 2. Node 3 is now at depth 2, below 2.union(4, 5): node 5 goes under 4, andrank[4]becomes 1.union(3, 1):find(3)sees thatparent[3]is 2, setsparent[3]toparent[2], which is 0, and stops at root 0.find(1)also returns 0. The roots match, sounionreturnsFalse. The rejected union still shortened node 3's path as a side effect.
Notice that rank[2] is still 1 even though node 2 is no longer a root. Ranks of non-root nodes are never read again, so stale values there do no harm.
How Fast Is It?
| Strategy | Worst-case cost per operation |
|---|---|
| Neither optimization | O(n) |
| Union by rank only | O(log n) |
| Path compression only | O(log n) amortized |
| Both | O(α(n)) amortized |
Here α is the inverse Ackermann function. It grows so slowly that α(n) ≤ 4 for any n that could fit in physical memory. "Amortized" means the bound holds on average over any sequence of operations. A single find can still walk a long path, but that walk flattens the path, so later operations get cheaper. Tarjan proved this bound, and he also proved that no pointer-based structure can do better. In practice, treat each operation as constant time.
For Kruskal's algorithm, this means the union-find work totals O(E α(V)). Sorting the edges dominates the running time.
Common Errors
- Linking non-roots. Writing
self.parent[b] = ainstead ofself.parent[find(b)] = find(a)reattaches onlyband leaves the rest of its old tree behind. The two groups do not actually merge. - Comparing parents instead of roots.
parent[a] == parent[b]is not a connectivity test. Two nodes at different depths in the same tree have different parents. Always comparefind(a) == find(b). - Bumping rank on every union. Rank should increase only when the two ranks are equal. If it increases every time, ranks no longer track height and the O(log n) proof breaks.
- Recursive find without union by rank. Full compression written recursively can raise
RecursionErrorin Python when a long chain forms. Use path halving, or pair recursion with union by rank. - Skipping the equal-roots check. Without
if ra == rb: return False, a root can become its own child, or a rank can grow when no merge happened. In Kruskal's algorithm, skipping the check also means you lose cycle detection.
Small Extensions
You will often want two extra pieces of state:
- A component count. Start
self.count = nand subtract 1 wheneverunionreturnsTrue. Kruskal's algorithm can then stop once the count reaches 1. In a disconnected graph, the final count is the number of trees in the spanning forest. - Component sizes. Keep
self.size[root]and add the absorbed root's size during each union. Single-linkage clustering uses this to report cluster sizes.
Exercise
Starting from DisjointSet(5), run union(0, 1), union(2, 3), union(1, 3), union(4, 3). Give the final parent and rank lists (path halving as implemented above).
Show answer
union(0,1): parent[1]=0, rank[0]=1. union(2,3): parent[3]=2, rank[2]=1. union(1,3): find(1)=0, find(3)=2, equal ranks, so parent[2]=0 and rank[0]=2. union(4,3): find(4)=4; find(3) halves the path, setting parent[3]=parent[2]=0, and returns 0. rank[4]=0 < rank[0]=2, so the roots swap and parent[4]=0. Final parent = [0, 0, 0, 0, 0], rank = [2, 0, 1, 0, 0].
Exercise
Prove that with union by rank, a tree whose root has rank r contains at least 2^r nodes, and conclude the maximum height of any tree.
Show answer
Use induction on unions. A new set has rank 0 and 1 = 2^0 node. A root's rank changes only when two roots of equal rank r merge, giving rank r+1 and at least 2^r + 2^r = 2^(r+1) nodes. When the ranks differ, the higher root keeps its rank and gains nodes, so the bound still holds. Since a tree holds at most n nodes, r ≤ log2 n. Without compression, height equals rank, so height is at most log2 n.
Exercise
A colleague's union is self.parent[self.find(b)] = self.find(a) with no rank and no equal-roots check. Name one input sequence where this is incorrect, not merely slow.
Show answer
Call union(0, 0), or call union(a, b) when a and b are already connected. Both finds return the same root r, and the code sets parent[r] = r. The structure stays intact, but union cannot report that no merge happened, so a caller like Kruskal's algorithm would wrongly accept a cycle-forming edge. Any component count kept alongside it would also be decremented incorrectly.