Sub topic 7
Disjoint Sets: Union by Rank and Path Compression
Kruskal's algorithm needs a quick answer to one question: are vertices u and v already connected by the edges chosen so far? If they are, adding edge (u, v) would close a cycle. A disjoint-set structure, also called union-find, answers this in nearly constant time.
This chapter assumes you know Python classes and lists, Big-O notation, and what a cycle in a graph is.
The Working Model
A disjoint-set structure keeps a collection of non-overlapping sets. Each set is stored as a tree. Every element points to a parent, and the root of each tree is the set's representative. It supports two operations:
find(x)follows parent pointers fromxup to the root and returns that root. Two elements are in the same set exactly when they have the same root.union(a, b)finds both roots. If the roots differ, it makes one root the child of the other, which merges the two sets.
At the start, each element is its own root, so n elements form n sets of one element each. In Kruskal's algorithm, each set is a connected component of the forest built so far.
The Two Optimizations
If you link roots without any rule, the trees can grow into long chains, and find then costs O(n). Two techniques prevent this.
Union by rank. Each root stores a rank, which is an upper bound on its tree's height. When merging, the root with the lower rank goes under the root with the higher rank. A rank goes up only when two trees of equal rank are merged. With this rule alone, tree height stays at O(log n).
Path compression. During find, nodes on the path are re-pointed closer to the root, so later lookups take fewer steps. The code below uses path halving, a one-pass version of the idea: each visited node is pointed at its grandparent. Full path compression points every node on the path directly at the root. Both versions have the same asymptotic bound.
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(5)
print(ds.union(0, 1)) # True
print(ds.union(2, 3)) # True
print(ds.union(1, 3)) # True
print(ds.union(0, 3)) # False: 0 and 3 are already connected
print(ds.find(3) == ds.find(1)) # True
print(ds.find(4)) # 4: still in its own setWhen union returns False, Kruskal's algorithm has found an edge that would form a cycle, so it skips that edge.
Common Errors
| Mistake | Consequence |
|---|---|
| Linking `a` to `b` directly instead of linking their roots | Sets split or merge incorrectly |
| Comparing `parent[a] == parent[b]` to test whether two elements are in the same set | False negatives; you must compare `find(a)` with `find(b)` |
| Raising the rank on every union | Ranks drift upward and no longer bound the height |
| Writing `find` recursively for large n | Python's recursion limit can be hit before compression flattens the tree |
| Updating rank on a non-root | Rank only has meaning at roots; the update is wasted |
Exercise
In the demo above, what is the parent list right after union(1, 3), and what does it become after the call union(0, 3)?
Show answer
After union(1, 3) it is [0, 0, 0, 2, 4]: roots 0 and 2 both have rank 1, so 2 goes under 0 and rank[0] becomes 2. During union(0, 3), find(3) applies path halving and sets parent[3] to its grandparent 0, so the list becomes [0, 0, 0, 0, 4]. The union then returns False.
Exercise
Using union by rank alone, without path compression, why can a tree of rank r not have fewer than 2^r elements?
Show answer
A root's rank rises to r only when two trees of rank r-1 are merged. By induction, each of those trees has at least 2^(r-1) elements, so the merged tree has at least 2^r. It follows that rank, and therefore height, is at most log2 n.