Union-find: grouping things and detecting cycles
A tiny structure that answers "are these two connected?" and merges groups, in almost constant time. Parent array, union by size, path compression, and the problems it solves.
In short
Union-find (disjoint set union) keeps items in groups. find(x) returns the group's representative (root); union(a, b) merges two groups. With union by size and path compression both are effectively O(1).
The idea: a forest of parent pointers
Every item points to a parent; a root points to itself. Two items are in the same group exactly when find takes them to the same root. To merge, hang one root under the other.
set size (at roots)
1parent = list(range(n))2size = [1] * n34def find(x):5 while parent[x] != x:6 parent[x] = parent[parent[x]]7 x = parent[x]8 return x910def union(a, b):11 ra, rb = find(a), find(b)12 if ra == rb:13 return False14 if size[ra] < size[rb]:15 ra, rb = rb, ra16 parent[rb] = ra17 size[ra] += size[rb]18 return True
Variables
Why it's so fast
Union by size
- Always hang the smaller tree under the bigger one
- Keeps trees shallow: height ≤ log n
Path compression
- While walking to the root, point nodes closer to it
- Future finds on those nodes are almost instant
Together they give amortised O(α(n)) per operation, where α is the inverse Ackermann function: below 5 for any input you will ever see. Treat it as constant.
What it's for
| Problem | How union-find helps |
|---|---|
| Number of connected components / provinces | Union every edge, count the roots at the end |
| Does adding this edge create a cycle? | If both ends already share a root, yes |
| Redundant connection | The first edge whose ends are already connected |
| Kruskal's minimum spanning tree | Sort edges, add one only if it joins two different sets |
| Grouping by equivalence (accounts, synonyms) | Union the items that are equal |
Key takeaways
- 01find returns the root; two items are connected when their roots match.
- 02union hangs one root under the other; if the roots match, the edge closes a cycle.
- 03Union by size + path compression: effectively O(1) per operation.
- 04Great for components, cycle detection and Kruskal; it cannot undo a union.
Check your understanding
1 of 3
How do you know two nodes are in the same group?
Related topics
BFS & DFS
A graph is nodes and edges. BFS uses a queue and explores in rings: the first time it reaches a node is via a shortest path (unweighted). DFS uses a stack (or recursion) and dives deep. Both cost O(V + E). Always keep a visited set, or cycles will loop forever.
10 min read →Topological sort
In a directed acyclic graph (DAG) a topological order puts every node after its prerequisites. Kahn's algorithm: repeatedly take a node with in-degree 0, remove it, and lower its neighbours' in-degree. If you can't order all nodes, there is a cycle. Cost: O(V + E).
8 min read →