Sub topic 8
Path Compression and Union by Size
The previous chapter built union-find from two operations. find(x) follows parent pointers up to a root, and union(a, b) links one root under another. That version is correct, but some sequences of unions make it slow. This chapter covers the two standard fixes, shows why each one works, and explains what they cost together.
This chapter assumes you have read the previous one. It also assumes you can read a Python class, follow a while loop over parent pointers, and know what amortized complexity means: an average cost per operation over a whole sequence of operations, not a promise about any single one.
The Problem: Trees That Degrade into Chains
find costs as much as the depth of the node it starts from. Without any rule about which root goes under which, an unlucky order of unions can build a tree that is one long path. A path of n nodes has depth n − 1, so each find from the bottom takes O(n) steps. Over m operations, the total becomes O(m · n), which is worse than running a single BFS.
The two fixes target different parts of the problem:
- Union by size controls how trees grow. It always attaches the smaller tree under the root of the larger one, so trees stay shallow.
- Path compression repairs trees after the fact. Every
findpoints each node it visits directly at the root, so laterfindcalls on those nodes take one step.
An Experiment You Can Run
The class below lets you switch each optimization on or off. It builds the worst case for naive linking, calling union(i, i + 1) for every i, and then reports the deepest node in the structure.
class DSU:
def __init__(self, n, by_size=True, compress=True):
self.parent = list(range(n))
self.size = [1] * n
self.by_size = by_size
self.compress = compress
def find(self, x):
root = x
while self.parent[root] != root:
root = self.parent[root]
if self.compress:
while self.parent[x] != root:
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.by_size and self.size[ra] > self.size[rb]:
ra, rb = rb, ra
# ra is now the smaller (or equal) tree; attach it under rb
self.parent[ra] = rb
self.size[rb] += self.size[ra]
return True
def depth(self, x):
d = 0
while self.parent[x] != x:
x = self.parent[x]
d += 1
return d
def max_depth(ds):
return max(ds.depth(x) for x in range(len(ds.parent)))
n = 1000
for by_size, compress in [(False, False), (False, True), (True, False), (True, True)]:
ds = DSU(n, by_size, compress)
for i in range(n - 1):
ds.union(i, i + 1)
print(f"by_size={by_size!s:5} compress={compress!s:5} max depth={max_depth(ds)}")
# Compression alone: one expensive find flattens the chain
ds = DSU(n, by_size=False, compress=True)
for i in range(n - 1):
ds.union(i, i + 1)
print("before find(0):", max_depth(ds))
ds.find(0)
print("after find(0): ", max_depth(ds))Output:
by_size=False compress=False max depth=999
by_size=False compress=True max depth=999
by_size=True compress=False max depth=1
by_size=True compress=True max depth=1
before find(0): 999
after find(0): 1The second line is worth a closer look. Path compression did nothing while the chain was being built. Each union(i, i + 1) called find only on nodes that were still roots, so no path existed to compress. Compression is lazy: it never stops a deep tree from forming. It makes you pay for the depth once, on the first find that walks it, and then removes the depth for good. Union by size works the other way. It stops deep trees from forming at all.
How Union by Size Bounds the Height
Union by size keeps a count of nodes for each root and attaches the smaller root under the larger one. This guarantees that every tree has height at most log₂ n.
The argument follows a single node x:
- The depth of x grows by one only when the root of x's tree is linked under another root.
- Under union by size, that happens only when the other tree is at least as large as x's tree.
- So each time x gets deeper, the tree containing x at least doubles in size.
- A tree cannot hold more than n nodes, so x's tree can double at most log₂ n times.
Every find therefore costs O(log n) in the worst case, even with no compression.
Union by Rank: The Common Alternative
Many textbooks use rank instead of size. Rank is an upper bound on a tree's height. It increases only when two trees of equal rank are merged.
class DSURank:
def __init__(self, n):
self.parent = list(range(n))
self.rank = [0] * n
def find(self, x):
root = x
while self.parent[root] != root:
root = self.parent[root]
while self.parent[x] != root:
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
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 = DSURank(5)
ds.union(0, 1)
ds.union(2, 3)
ds.union(0, 2)
print(ds.rank[ds.find(3)]) # 2
print(ds.find(1) == ds.find(3)) # TruePath compression lowers the real height of a tree, but rank is never decreased. Rank therefore becomes an upper bound on height rather than the exact height. That is fine, because the complexity proof needs only the bound. Size and rank give the same asymptotic guarantees. Size has a practical advantage: it answers "how big is this component?" for free, and many problems ask exactly that.
How Path Compression Rewires a Tree
find makes two passes. The first walks up to locate the root. The second walks the same path again and sets each node's parent to the root.
Compression changes only parent pointers along the path that find walked. Nodes hanging off that path keep their parents, but they move closer to the root as a side effect, because their ancestors now sit directly under it.
Path Halving and Path Splitting
Two one-pass variants give the same asymptotic bound and skip the second loop.
def find_halving(parent, x):
# Point every other node on the path to its grandparent
while parent[x] != x:
parent[x] = parent[parent[x]]
x = parent[x]
return x
def find_splitting(parent, x):
# Point every node on the path to its grandparent
while parent[x] != x:
nxt = parent[x]
parent[x] = parent[nxt]
x = nxt
return x
p = [1, 2, 3, 4, 4] # chain 0 -> 1 -> 2 -> 3 -> 4
print(find_halving(p, 0), p) # 4 [2, 2, 4, 4, 4]
q = [1, 2, 3, 4, 4]
print(find_splitting(q, 0), q) # 4 [2, 3, 4, 4, 4]Halving touches about half the nodes on the path and splitting touches all of them. Neither flattens a path to depth 1 in one call. Repeated calls do the job, and the amortized bound matches full compression.
Avoid Recursive find in Python
The textbook one-liner is parent[x] = find(parent[x]). It is correct, but it recurses once per level. Without union by size, the chain in the experiment above has depth 999. Push n up to a few thousand and the first find(0) raises RecursionError, because Python's default recursion limit is 1000. The iterative versions in this chapter avoid that limit.
What the Combination Costs
| Variant | Worst case for one `find` | Amortized per operation | Extra memory |
|---|---|---|---|
| Naive linking, no compression | O(n) | O(n) | `parent` only |
| Path compression only | O(n) | O(log n) | `parent` only |
| Union by size or rank only | O(log n) | O(log n) | `parent` + `size`/`rank` |
| Both | O(log n) | O(α(n)) | `parent` + `size`/`rank` |
α(n) is the inverse Ackermann function. It grows so slowly that α(n) ≤ 4 for any n that fits in physical memory. Robert Tarjan proved this bound in 1975, and it is tight: no pointer-based union-find can do better amortized. In practice you can treat each operation as constant time, so m operations on n elements cost about O(n + m).
Keep two details in mind:
- The α(n) bound is amortized. A single
findcan still take O(log n) steps, because union by size caps the height. If you need a strict per-operation latency, union by size is what provides it, not compression. - Path compression writes to memory during
find. That matters when several threads share the structure, and it rules out afindthat keeps the structure unchanged. Union by size alone keepsfindread-only.
Common Errors
- Linking non-roots.
parent[a] = binstead ofparent[ra] = rbattaches a subtree in the middle of another tree and quietly corrupts sizes. - Updating the wrong size. After the swap, add the smaller tree's size to the surviving root:
size[rb] += size[ra]inDSU, whererais the smaller root. - Testing connectivity with
parent[a] == parent[b]. Two nodes can share a root while having different parents. Always comparefind(a) == find(b). - Skipping the
ra == rbcheck. Without it, a redundant union adds a tree's size to itself and, in the component-count version, decrements the count incorrectly.
Exercise
Starting from DSU(8) with both optimizations on, you call union(0,1), union(2,3), union(4,5), union(6,7), union(0,2), union(4,6), union(0,4). What is the maximum depth of any node, and why can it not be larger?
Show answer
The maximum depth is 3. Each round merges two trees of equal size (1+1, then 2+2, then 4+4), and every merge adds one level to the nodes of the linked tree. Every node is linked under a new root at most three times, so the deepest nodes sit at depth 3. The finds inside these unions start at roots or depth-1 nodes, so compression flattens nothing. This is the worst case for union by size: height log2(8) = 3, which matches the doubling bound.
Exercise
A colleague drops union by size and keeps only path compression, arguing that "compression flattens everything anyway." Using the experiment in this chapter, describe a workload where this choice causes a problem.
Show answer
Compression acts only on paths that a find walks, so a series of unions between roots can build a chain of depth n − 1 with no compression at all. The first find on the deepest node then costs O(n). Amortized cost stays logarithmic, but a latency-sensitive system sees occasional O(n) spikes, and a recursive find would overflow the stack. Union by size caps every find at O(log n).
Exercise
Why is it safe that union by rank never lowers a rank after path compression shortens a tree?
Show answer
The analysis needs rank only as an upper bound on height, and that a root of rank r has at least 2^r nodes. Compression can only shrink heights and never changes which nodes belong to a tree, so both properties still hold. Recomputing exact heights would cost time and gain nothing.