Union by rank and path compression
🌍 In real life. In a big company, a new employee who wants the boss's signature can ask their manager, who asks theirs, and so on up the chain. If the chain is long, every request is slow. Two habits keep it short: when two teams merge, the smaller team goes under the bigger one's boss, not the other way round; and once you have found the top boss, you remember to go straight to them next time.
Union-Find has the same two tricks. The idea in one sentence: union by rank hangs the shorter tree under the taller one, so trees stay short, and path compression points every item a find passed straight at the leader, so the next find from them takes one step.
Its words:
- rank: a number kept for each leader, an upper bound on its tree's height; it starts at 0
- union by rank: link the leader with the smaller rank under the one with the bigger rank; only when the ranks are equal does the new leader's rank grow by 1
- path compression: after a find reaches the leader, set the parent of every item on the way to the leader
Step by step, the chain from Lesson 53.1, now with path compression:
- unions have built the chain 0 → 1 → 2 → 3 → 4
find(0)walks all 4 links to the leader 4- then it walks the path again and points 0, 1 and 2 straight at 4
- a second
find(0)takes 1 link
Watch the chain flatten:
Now union by rank, together with path compression. Each leader shows its rank. Equal ranks make the winner's rank grow; a shorter tree simply goes under, and nothing gets taller:
Why union by rank keeps trees short. A leader's rank only grows when two trees of the same rank r join, and each of those has at least 2^r items, so a tree of rank r + 1 has at least 2^(r+1). A tree of n items therefore has rank at most log₂ n, and a find walks at most that many links: for a million items, at most 19.
Why path compression helps on top. Every find makes the items it passed point at the leader, so the work spent on a long path is paid only once. With both tricks together, a long run of finds and unions costs, on average, a number of steps per operation that is below 5 for any group you could ever store. Computer scientists write this as O(α(n)), where α is the inverse Ackermann function, which grows almost unbelievably slowly; in practice, think of each operation as O(1).
class DSU:
def __init__(self, n):
self.parent = list(range(n))
self.rank = [0] * n # an upper bound on each tree's height
self.groups = n
def find(self, x):
root = x
while self.parent[root] != root:
root = self.parent[root]
while self.parent[x] != root: # path compression: point the path at the leader
nxt = self.parent[x]
self.parent[x] = root
x = nxt
return root
def union(self, a, b):
ra, rb = self.find(a), self.find(b)
if ra == rb:
return False
if self.rank[ra] < self.rank[rb]:
ra, rb = rb, ra # union by rank: the shorter tree goes under
self.parent[rb] = ra
if self.rank[ra] == self.rank[rb]:
self.rank[ra] += 1
self.groups -= 1
return True
d = DSU(6)
for a, b in [(0, 1), (2, 3), (0, 2), (4, 5), (4, 0)]:
print("union", a, b, d.union(a, b), "rank", d.rank)
print(d.find(5), d.parent, "groups", d.groups)Mistakes and edge cases.
- growing the rank on every union: only equal ranks make the tree taller; growing it always makes rank meaningless
- ranking by the items, not the leaders: compare
rank[ra]andrank[rb]of the two leaders - compressing before you know the leader: the first loop must reach the leader; only then can the second loop point the path at it
- recursion in find: the neat recursive version
parent[x] = find(parent[x])can hit Python's recursion limit on a long chain built before any compression; the two-loop version can't - ranks after compression: compression makes trees shorter but leaves the ranks alone, so a rank is an upper bound on the height, not the exact height
Quiz
What does this print?
class DSU: def __init__(self, n): self.parent = list(range(n)) self.rank = [0] * n # an upper bound on each tree's height self.groups = n def find(self, x): root = x while self.parent[root] != root: root = self.parent[root] while self.parent[x] != root: # path compression: point the path at the leader nxt = self.parent[x] self.parent[x] = root x = nxt return root def union(self, a, b): ra, rb = self.find(a), self.find(b) if ra == rb: return False if self.rank[ra] < self.rank[rb]: ra, rb = rb, ra # union by rank: the shorter tree goes under self.parent[rb] = ra if self.rank[ra] == self.rank[rb]: self.rank[ra] += 1 self.groups -= 1 return True d = DSU(5) d.parent = [1, 2, 3, 4, 4] print(d.find(0), d.parent)What does this print?
class DSU: def __init__(self, n): self.parent = list(range(n)) self.rank = [0] * n # an upper bound on each tree's height self.groups = n def find(self, x): root = x while self.parent[root] != root: root = self.parent[root] while self.parent[x] != root: # path compression: point the path at the leader nxt = self.parent[x] self.parent[x] = root x = nxt return root def union(self, a, b): ra, rb = self.find(a), self.find(b) if ra == rb: return False if self.rank[ra] < self.rank[rb]: ra, rb = rb, ra # union by rank: the shorter tree goes under self.parent[rb] = ra if self.rank[ra] == self.rank[rb]: self.rank[ra] += 1 self.groups -= 1 return True d = DSU(3) d.union(0, 1) d.union(1, 2) print(d.rank, d.parent)With union by rank, a tree of 1,000,000 items is at most how tall?
- 19 links, since a rank r tree has at least 2^r items
- 999,999 links
- 1 link
When does union by rank make a leader's rank grow?
- Only when the two leaders have the same rank
- On every union
- When the smaller tree goes under
This DSU's ranks keep growing even when a short tree joins a tall one. Which line is wrong?
def union(self, a, b): ra, rb = self.find(a), self.find(b) if ra == rb: return False if self.rank[ra] < self.rank[rb]: ra, rb = rb, ra self.parent[rb] = ra self.rank[ra] += 1 return True
Coding tasks
Write
find(parent, x)with path compression: return the leader ofx, and on the way point every item on the path straight at the leader.Finish
class DSU(n)withfind(with path compression) andunion(a, b)by rank, which returnsTruewhen it merged two groups andFalseotherwise, and keepsgroups, the number of groups, up to date.