Sub topic 8
Path Compression and Union by Size
This chapter assumes you have read the previous chapter's basic union-find, where find follows parent pointers to a root and union links one root under another. You should also be comfortable with Big-O notation. Without the two techniques covered here, union-find can do worse than the BFS approach it is meant to replace.
The Problem: Tall Trees
The cost of find equals the depth of the vertex in its tree. A naive union links roots in whatever order the arguments arrive, and the wrong order of unions builds a chain. Once that happens, every find near the bottom walks the whole chain, which costs O(n).
class NaiveDSU:
def __init__(self, n):
self.parent = list(range(n))
def find(self, x):
while self.parent[x] != x:
x = self.parent[x]
return x
def union(self, a, b):
ra, rb = self.find(a), self.find(b)
if ra != rb:
self.parent[ra] = rb
class CompressedDSU(NaiveDSU):
def find(self, x):
root = x
while self.parent[root] != root:
root = self.parent[root]
while self.parent[x] != root:
nxt = self.parent[x]
self.parent[x] = root
x = nxt
return root
class SizedDSU(NaiveDSU):
def __init__(self, n):
super().__init__(n)
self.size = [1] * n
def union(self, a, b):
ra, rb = self.find(a), self.find(b)
if ra == rb:
return
if self.size[ra] < self.size[rb]:
ra, rb = rb, ra
self.parent[rb] = ra
self.size[ra] += self.size[rb]
def max_depth(parent):
best = 0
for x in range(len(parent)):
d = 0
while parent[x] != x:
x = parent[x]
d += 1
best = max(best, d)
return best
n = 1000
for cls in (NaiveDSU, CompressedDSU, SizedDSU):
ds = cls(n)
for i in range(n - 1):
ds.union(i, i + 1)
print(cls.__name__, "after unions:", max_depth(ds.parent))
ds.find(0)
print(cls.__name__, "after find(0):", max_depth(ds.parent))
# NaiveDSU after unions: 999
# NaiveDSU after find(0): 999
# CompressedDSU after unions: 999
# CompressedDSU after find(0): 1
# SizedDSU after unions: 1
# SizedDSU after find(0): 1Union by Size
Union by size always attaches the root of the smaller tree under the root of the larger one. A vertex gets one level deeper only when its tree joins a tree at least as large, so its tree's size at least doubles each time. Sizes cannot exceed n, so this happens at most log₂ n times. Every tree therefore has depth O(log n), whatever order the unions arrive in.
Union by rank is the classic alternative. It stores an upper bound on tree height instead of a vertex count and gives the same guarantee. Size is usually more useful in practice because it also tells you how big each component is.
Path Compression
Path compression changes find. The first loop locates the root. The second loop walks the same path again and points every vertex on it directly at the root. The output above shows that one find(0) on a 999-long chain flattens the whole tree. The second loop is written iteratively on purpose: a recursive version would exceed Python's default recursion limit of 1000 on a chain this long.
Combined Cost
| Technique | Cost per operation |
|---|---|
| Neither | O(n) worst case |
| Union by size only | O(log n) worst case |
| Path compression only | O(log n) amortized |
| Both | O(α(n)) amortized |
The function α is the inverse Ackermann function. It is at most 4 for any n you could store in memory, so in practice each operation takes constant time. Amortized means the bound holds on average over a long sequence of operations. A single find can still be slow, but it flattens the path it walks, so later calls on that path are cheap.
Exercise
In the SizedDSU above, why does the tree stay at depth 1 when unions are applied in the order (0,1), (1,2), (2,3), ...?
Show answer
After the first union, vertex 0 is the root of a tree of size 2. Each later union compares that tree with a single vertex of size 1, so the single vertex goes under root 0. Every vertex ends up pointing directly at 0.
Exercise
Suppose you use union by size without path compression on n = 1,048,576 vertices. What is the most parent pointers any find can follow?
Show answer
20. A vertex's depth increases only when its tree size at least doubles, and 2^20 = 1,048,576, so depth cannot exceed log₂ n = 20.