Parent trees represent groups
Choose Build a bad chain with the union by rank and path compression options off. A find can then follow a long chain. Turn on union by rank and rebuild: attaching the shallower tree under the deeper one keeps the height logarithmic. Equal-rank roots can be joined and the resulting rank increased by one.
Path compression shortens later searches
During find, path compression makes nodes on the path point directly to the root, so future searches traverse fewer links. Use Find(a) — show path to see the links update. Union(a, b) merges the two groups; Same group? checks whether two elements share a representative.
With both union by rank and path compression, a sequence of operations has amortized O(α(n)) cost per operation, where α is the inverse Ackermann function. It grows so slowly that it is below 5 for any practical input size, but the bound is not exactly constant.
| Heuristic | Effect |
|---|
| Union by rank | Keeps tree height logarithmic without compression |
| Path compression | Flattens paths during find |
| Both | Amortized inverse-Ackermann cost across operations |
Where it is useful
Union-Find fits connectivity problems where groups merge but never split. Kruskal’s minimum spanning tree algorithm uses it to check whether an edge would connect vertices already in the same component. It also supports connected-component tracking in undirected graphs and grouping equivalent identifiers.
What it cannot do
The structure does not efficiently split a group or remove an edge while preserving general dynamic connectivity. If the application needs deletions, use a structure designed for that case or an offline rollback variant. Union-Find also does not answer directed reachability or shortest-path questions.
Common mistakes with Union-Find
- Unioning elements instead of their roots: attach representatives, not arbitrary nodes.
- Counting a repeated union as a new merge: if roots match, the number of components does not change.
- Calling the bound constant: inverse-Ackermann is effectively tiny in practice but remains a function.
- Using it for deletions: ordinary disjoint-set union only merges components.