Sub topic 18
Union-find with union by rank and path compression
This chapter assumes you know Big-O notation, arrays, and basic graph terms such as vertices, edges, and connected components. It also assumes you can read short Python. Kruskal's algorithm in the next chapters depends on this structure.
The problem
A disjoint-set union (also called union-find) keeps a collection of non-overlapping sets and supports three operations:
make_set(x)creates a set containing onlyx.find(x)returns a representative of the set holdingx. Two elements are in the same set exactly when their representatives are equal.union(a, b)merges the sets holdingaandb.
Each set is stored as a tree. Every element points to a parent, and the root points to itself. The root is the representative. An array parent holds all the pointers.
Why the naive forest is slow
If union simply hangs one root under another, an unlucky order builds a chain. Joining 1 under 2, 2 under 3, and so on gives a path of length n. After that, every find on the deepest element costs O(n). A sequence of m operations can then cost O(mn).
Two independent fixes keep the trees shallow.
Union by rank
Each root stores a rank, an upper bound on its tree height. When merging two roots:
- If their ranks differ, attach the lower-rank root under the higher-rank root. No rank changes.
- If their ranks are equal, attach either one under the other and increase the new root's rank by 1.
A tree of rank r always has at least 2^r nodes. This follows by induction, because rank only grows when two trees of equal rank, each with at least 2^(r-1) nodes, are merged. So rank is at most log2 n, and every find costs O(log n).
Path compression
During find(x), every node on the path from x to the root is re-pointed directly at the root. The first find pays for the walk. Later find calls on those nodes take one step.
Compression changes tree heights but not ranks. Rank is therefore only an upper bound on height, and you must not decrease it when compressing.
Implementation
class DisjointSet:
def __init__(self, n):
self.parent = list(range(n))
self.rank = [0] * n
self.count = n # number of separate sets
def find(self, x):
root = x
while self.parent[root] != root:
root = self.parent[root]
while self.parent[x] != root: # second pass: compress the path
self.parent[x], x = root, self.parent[x]
return root
def union(self, a, b):
ra, rb = self.find(a), self.find(b)
if ra == rb:
return False # already in the same set
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
self.count -= 1
return True
ds = DisjointSet(6)
ds.union(0, 1)
ds.union(2, 3)
ds.union(0, 2)
ds.union(4, 5)
ds.union(3, 5)
print(ds.parent) # [0, 0, 0, 0, 0, 4]
print(ds.find(5)) # 0
print(ds.parent) # [0, 0, 0, 0, 0, 0]
print(ds.count) # 1The trace explains the output. The first three unions build a rank-2 tree rooted at 0. The union (4, 5) builds a rank-1 tree rooted at 4. In union(3, 5), the roots are 0 (rank 2) and 4 (rank 1), so 4 goes under 0. Node 5 still points to 4 until find(5) compresses it.
union returns True when it merges two sets and False when both elements were already together. That return value is how Kruskal's algorithm detects a cycle.
Complexity
| Variant | Amortized cost per operation |
|---|---|
| Naive linking | O(n) worst case |
| Union by rank only | O(log n) |
| Path compression only | O(log n) |
| Both together | O(α(n)) |
Here α is the inverse Ackermann function. It grows so slowly that α(n) is at most 4 for any input that fits in physical memory. For exam purposes, treat m operations on n elements as O(m α(n)), nearly linear. Initialization costs O(n).
The cost is amortized, so a single find can still be expensive. Over a long sequence the total stays small.
Common errors
- Linking elements instead of roots. Setting
parent[a] = bwithout callingfindfirst corrupts the structure. - Forgetting the equal-root check. Without it,
unionof two elements in the same set can raise a rank or create a cycle in the parent pointers. - Raising rank on every union. Rank increases only when the two ranks are equal.
- Treating rank as exact height. After compression it overstates height. That is intended.
- Writing
findrecursively without thinking about depth. With union by rank the depth is at most log n, so recursion is safe. Without it, long chains can overflow Python's recursion limit.
Where it is used
Kruskal's algorithm sorts the edges, then calls union(u, v) for each one. It keeps an edge only when union returns True. The sort costs O(E log E), which dominates the O(E α(V)) spent on union-find. The same structure counts connected components in a changing graph and detects a cycle in an undirected graph while edges are added one at a time.
Exercise
Starting from 5 singletons labelled 0 to 4, you run union(0,1), union(2,3), union(1,3), union(4,0), using union by rank where ties attach the second root under the first. What is the final root of the whole set, and what is rank[root]?
Show answer
union(0,1): ranks tie, 1 goes under 0, rank[0]=1. union(2,3): 3 goes under 2, rank[2]=1. union(1,3): the roots are 0 and 2 with equal rank 1, so 2 goes under 0 and rank[0]=2. union(4,0): the roots are 4 (rank 0) and 0 (rank 2), so 4 goes under 0 and no rank changes. The root is 0 and rank[0]=2.
Exercise
Why is it safe to use path compression without ever decreasing any rank, and what does the rank mean after compression?
Show answer
Rank is only used to decide which root goes under which, and any upper bound on height serves that purpose. Compression can only make trees shallower, so rank remains a valid upper bound on height, though not always the exact height. The log n bound on rank from union by rank still holds.