Skip to content

Path Compression

Lesson 2 of 4 · 5 min

Path Compression

Step 1 of 10

A chain: 0 points at 1, 1 at 2, up to 4. Every find has to re-walk the whole thing.

The Idea

Unions can build a long chain, and then every find re-walks it. But the walk already learned the answer.

So make a second pass over the same path and point each node straight at the root. The path you paid for once is flat for everyone who uses it afterwards.

Real-World Example

A phone menu that forwards you through three departments before reaching the one person who can help. The second time you call their direct number. Nobody re-derives the route because the route was worth writing down.

The Code

Your turn

What does this print?

parent = [1, 2, 2]
def find(x):
  root = x
  while parent[root] != root:
      root = parent[root]
  while parent[x] != root:
      parent[x], x = root, parent[x]
  return root
find(0)
print(parent)

Mini quiz

1 / 3

When does path compression happen?