awelgorithms

Flatten on the way to the root

Updated

Path compression: after you know the root r, set parent[u] = r for every u on the path. The chain becomes a star under r.

What to focus on

Compression is extra writes during find. It does not change who the root is. A path 3→2→1→0 becomes 3→0, 2→0, 1→0.

Worked examples

two-edge path

a = [0, 1, 2, 3], parent=[0,0,1,3], find(2)
  1. path 2 → 1 → 0
  2. parent[2]=0, parent[1]=0

Result: parent=[0,0,0,3]

three-edge path

a = [0, 1, 2, 3], parent=[0,0,1,2], find(3)
  1. path 3 → 2 → 1 → 0
  2. all point at 0

Result: parent=[0,0,0,0]

already flat

a = [0, 1], parent=[0,0], find(1)
  1. parent[1] already 0

Result: parent=[0,0]

Try it

Write findCompress(parent, x). parent is the parent array. x is the start index. After you know the root r, set parent[u] = r for every u on the path. Return the updated parent array. The root itself does not change. find(2) flattens parent=[0, 0, 1, 3] to [0, 0, 0, 3]. find(3) flattens parent=[0, 0, 1, 2] to [0, 0, 0, 0]. parent=[0, 0] stays flat.

x is a live index. parent forms a tree. Compression rewrites nodes on the path to the existing root.