Union-Find
A forest of trees representing disjoint groups. find(x) returns the root; union(a, b) merges groups. With path compression and union by rank, operations are effectively constant.
The idea
parent[i] = i at the start. find walks to the root and flattens the path (path compression). union links the shorter tree under the taller (rank or size).
Use it when edges arrive over time: “now a and b are connected — how many components left?” DFS from scratch each time is too slow.
Interns can answer component-count with DFS. Union-find is the mid/senior tool, and the Kruskal MST backbone.
Worked example
Components after undirected edges
n nodes labeled 0..n−1 and a list of undirected edges. How many connected components? Example: n = 5, edges [[0,1],[1,2],[3,4]] → 2.
- Start with n components.
- For each edge, if find(a) !== find(b), union and decrement.
- If they already share a root, the edge is redundant.