Sub topic 7
Path compression: flattening as you search
This chapter assumes you know the parent-pointer forest, the find and union operations, and why a naive union can build a long chain. Path compression is the second fix for that chain. Union by size controls how trees grow. Path compression repairs a tree during lookups.
The idea
A find walks from a node up to its root. Every node on that walk has the same root. After you learn the root, you can point each of those nodes straight at it. The next find on any of them takes one step.
The work is free in the asymptotic sense. You already visited every node on the path, so repointing them only doubles the cost of that one call.
Two-pass implementation
The iterative version makes two passes. The first pass finds the root. The second pass walks the same path again and repoints each node.
parent = [1, 2, 3, 4, 5, 5] # chain 0 -> 1 -> 2 -> 3 -> 4 -> 5
def find(x):
root = x
while parent[root] != root:
root = parent[root]
# second pass: point every node on the path directly at the root
while parent[x] != root:
parent[x], x = root, parent[x]
return root
print(find(0)) # 5
print(parent) # [5, 5, 5, 5, 5, 5]One call on the deepest node turned the whole chain into a star. A later find(0) or find(3) does one comparison and returns.
Recursive form and variants
You can write compression recursively:
def find(x):
if parent[x] != x:
parent[x] = find(parent[x])
return parent[x]This is shorter, but its recursion depth equals the path length. Python's default limit is about 1000 frames, so a long chain raises RecursionError. Prefer the iterative version unless you also use union by size, which keeps paths short.
Two cheaper variants exist:
| Variant | What it does | Passes |
|---|---|---|
| Full compression | Every node on the path points to the root | Two |
| Path halving | Each visited node points to its grandparent | One |
Path halving updates parent[x] = parent[parent[x]] and then moves x to the new parent. It needs no second pass and gives similar guarantees in practice.
What it does and does not guarantee
Path compression only changes the tree when you call find. A chain that nobody searches stays a chain. The first find on a deep node still costs the full depth. The saving comes from later calls.
On its own, path compression gives an amortized cost of O(log n) per operation. That means the total over m operations is bounded, even though a single call can be slow. Combined with union by size it gets much smaller, which the next chapter covers.
Compression also changes what size means. Moving nodes does not change which set they belong to, and size[root] still counts every member. Only roots keep a meaningful size, so never read size for a non-root node.
Common errors
- Compressing to the parent instead of the root. Each node must point at the root, not at the node one step up.
- Forgetting that
unionshould callfindon both arguments. If you link the raw arguments, you may attach a non-root and corrupt the sets. - Using the recursive form on large inputs without a raised recursion limit.
Exercise
Start with parent = [1, 2, 3, 3] (a chain 0 -> 1 -> 2 -> 3 with root 3). After one call to the two-pass find(1), what is the parent list, and which entry stays unchanged?
Show answer
The result is [1, 3, 3, 3]. The first pass finds root 3 starting from node 1. The second pass sets parent[1] = 3 and then parent[2] already equals 3, so it stops. Entry 0 is unchanged because node 0 was not on the searched path. It still points to 1, and a later find(0) takes two steps and compresses it.