Union-Find (Disjoint Set Union)
elements 0–9
Union
–
Pseudocode
1find(x):2 if parent[x] == x: return x // x is the root of its set3 root ← find(parent[x])4 parent[x] ← root // path compression5 return root6union(a, b):7 ra ← find(a); rb ← find(b)8 if ra == rb: they are already in the same set9 if rank[ra] < rank[rb]: swap ra and rb // union by rank10 parent[rb] ← ra; if the ranks were equal: rank[ra] ← rank[ra] + 1
Parent hops
0
Sets
0
Tallest tree
0
colourone set (tree); thick ring = rootfind path being climbedpointer just changed
What is Union-Find?
Union-Find, or Disjoint Set Union (DSU), keeps track of elements split into groups that never overlap. It answers two questions very fast: which group is x in? (find) and join the groups of a and b (union).
Each group is stored as a tree of parent pointers, and the root names the group. Find climbs to the root; union hangs one root under the other. Two small tricks, union by rank and path compression, keep the trees so flat that both operations are practically constant time. It is the engine behind Kruskal's and Borůvka's algorithms.
A set is a tree; its root is its name. Keep the trees flat.
Using the Visualizer
- • Type two elements (0–9) and press Union, Find or Connected?
- • Arrows point from a child to its parent; each colour is one set and the thick-ringed node is its root.
- • The parent and rank arrays at the bottom are exactly what the code stores.
- • Load the Worst-case chain and run Find(0) with path compression on: the whole chain collapses to point at the root. Turn the tricks off to see trees grow tall.
How It Works
Find
Follow parent[x] until an element is its own parent: that root names the set.
Path compression
Afterwards, point every node on the path straight at the root.
Union
Find both roots; if they differ, make one root the parent of the other.
Union by rank
Hang the tree with the smaller rank under the bigger one; equal ranks grow by one.
Implementation
Properties & Complexity
Time Complexity
- • Both tricks: O(α(n)) amortised per operation (α ≤ 4 in practice)
- • Only one trick: O(log n)
- • Neither: O(n) per find on a chain
Space & Properties
- • Space: O(n) for parent and rank
- • Union only: sets can merge but never split
Where It Is Used
- • Kruskal's MST: does this edge make a cycle?
- • Connected components as edges arrive one by one
- • Image segmentation and percolation simulations
- • Equivalence: merging accounts, type unification in compilers
Limitations
- • No splitting: you can't undo a union cheaply
- • No listing: getting all members of a set needs extra work