Why it matters

Any problem involving 'are these two things connected?' or 'merge these groups' is a candidate for union-find. It's shockingly fast and simple.

Advertisement

The architecture

Structure: array parent[], where parent[i] is i's parent (or i itself for roots). find follows parent pointers to root. union links one root under the other.

Optimizations: path compression (find flattens the path), union by rank (union attaches smaller tree under larger).

Union-Find operationsFindwalk to rootUnionlink rootsOptimizationscompression + rankWith both optimizations, operations are O(α(n)) — effectively constant for any n
DSU core operations.
Advertisement

How it works end to end

Path compression: during find, make every node on the path point directly to the root. Speeds up future finds.

Union by rank (or size): attach smaller tree under larger. Keeps tree depth small.

Applications: Kruskal's MST (union when adding edge if endpoints not connected), dynamic connectivity, offline min queries, image connected components.