Union-Find (Disjoint Set)

Difficulty
Importance

The problem

Some problems repeatedly need to answer 'are these two items in the same group' and 'merge these two groups into one,' as groups keep merging over time — recomputing group membership from scratch after every merge is far too slow for problems with many merges.

Why now

Arrays and lists already gave fast indexed storage; union-find is a deliberately narrow structure built on top of it, answering only two questions (same group? merge groups) as cheaply as possible instead of supporting general-purpose queries a more powerful structure would need to pay for.

Mental model

Union-find represents each group as a tree where every node points toward a representative root, and 'same group' is just 'do these two nodes point to the same root.' Two optimizations — path compression (flatten the tree on every lookup) and union by rank (attach the smaller tree under the larger) — together make both operations run in nearly constant time, amortized over many calls.

Requires

Helps

Unlocks

Used in

Projects

  • Implement union-find with both path compression and union by rank, then use it to detect whether adding a given edge to a graph would create a cycle
  • Use union-find to implement Kruskal's algorithm and compute a minimum spanning tree

Examples

  • Adding an edge between two nodes that union-find reports are already in the same set means that edge would create a cycle — checked in nearly O(1), no traversal needed
  • Without path compression, repeated finds can degrade to O(n) per call; with it, the tree flattens over time and finds approach O(1)

Resources

Mastery checklist