â Lab
ðē Union-Find â parent[], path compression, union by rank
Track connected sets with a parent array. find walks to the root and flattens the path; union attaches the shorter tree under the taller. Near-O(1) per op.
ab
elements
8
disjoint sets
8
find/union
âO(1)
a,b connected?
no
parent[i] â a root points to itself
0â0
root
1â1
root
2â2
root
3â3
root
4â4
root
5â5
root
6â6
root
7â7
root
what just happened (say it out loud)
Run an operation to see it step by step.
ėŽė: Union-Find answers 'are these in the same set?' in near-constant time by keeping a forest in a flat array. Path compression + union-by-rank keep the trees almost flat, which is why the amortized cost is the inverse-Ackermann Îą(n) â effectively O(1).
âķ deep-dive videos â âunion find disjoint set path compression union by rankâ