Union-find, also called a disjoint set union (DSU), maintains a collection of non-overlapping sets under two operations: find(x) returns a representative of x's set, and union(x, y) merges two sets. Stored as a forest of parent pointers and combined with union by size (or rank) and path compression, each operation costs O(α(n)) amortized, where α is the inverse Ackermann function: effectively a constant. It is the engine behind Kruskal's MST, dynamic connectivity and countless grouping problems.
Think of it like
Clubs with presidents
Every club has a president. To learn whether two people belong to the same club, each asks "who is my president?" by following the chain of who recruited whom until they reach someone who answers to nobody. When two clubs merge, one president simply starts reporting to the other, and the smaller club joins the larger one to keep chains short. Path compression is everyone on a chain remembering the president's name after asking once, so next time they answer instantly.
The interface
| Operation | Meaning |
|---|---|
make_set(x) | Create a new set containing only x (usually done for 0..n-1 up front). |
find(x) | Return the representative (root) of the set containing x. |
union(x, y) | Merge the sets containing x and y. Returns false if they were already the same set. |
connected(x, y) | find(x) == find(y). |
count / size(x) | Number of sets, and size of x's set (free with union by size). |
Each set is a rooted tree stored in a single parent array. The root is the representative and points to itself: parent[r] = r. find walks parent pointers up to the root; union links one root under the other. Nothing else is needed, which is why the structure is so fast and compact.
From naive to near-constant
Naive linking
If union attaches roots in an arbitrary direction, trees can degenerate into long chains. Calling union(0, 1), union(0, 2), union(0, 3), … with "attach find(a) under find(b)" builds the chain 0 → 1 → 2 → 3 → …, so find(0) costs O(n) and n operations cost O(n²).
# Naive: no balancing, no compression
def find_naive(x):
while parent[x] != x:
x = parent[x]
return x
def union_naive(a, b):
parent[find_naive(a)] = find_naive(b) # arbitrary direction: chains can form
# Full path compression (recursive, two passes in effect)
def find_compress(x):
if parent[x] != x:
parent[x] = find_compress(parent[x]) # point x straight at the root
return parent[x]Union by size or rank
Always attach the root of the smaller tree under the root of the larger one. A node's depth grows only when its tree is merged into one at least as large, so every time it gets one level deeper its tree at least doubles. A tree of n nodes can double at most log₂ n times.
Path compression and path halving
While find walks to the root it can rewrite the pointers it passed. Full compression points every node on the path directly at the root. Path halving makes every node on the path point to its grandparent, in a single iterative pass with no recursion. Both flatten the tree for future calls and both achieve the same amortized bound.
| Strategy | Single find (worst case) | Amortized per operation |
|---|---|---|
| Naive linking | O(n) | O(n) |
| Union by size or rank | O(log n) | O(log n) |
| Path compression only | O(n) | O(log n) |
| Union by size/rank + path compression | O(log n) | O(α(n)) |
The inverse Ackermann function
Robert Tarjan proved in 1975 that m operations on n elements with both optimizations take O(m · α(n)) time, and later results showed no structure of this kind can do better. α(n) is the inverse of the Ackermann function, which grows so explosively that its inverse barely moves.
| n | α(n) |
|---|---|
| 0 to 2 | 0 |
| 3 | 1 |
| 4 to 7 | 2 |
| 8 to 2,047 | 3 |
| 2,048 to far beyond 10⁸⁰ (the atoms in the observable universe) | 4 |
Worked example
Six elements 0..5, union by size (on ties the second root goes under the first) and path halving. The visualization above shows the same kind of forest reshaping as unions and finds run.
| Operation | parent after | Notes |
|---|---|---|
| start | [0, 1, 2, 3, 4, 5] | Six singleton sets |
| union(0, 1) | [0, 0, 2, 3, 4, 5] | Equal sizes: 1 goes under 0 |
| union(2, 3) | [0, 0, 2, 2, 4, 5] | 3 goes under 2 |
| union(1, 3) | [0, 0, 0, 2, 4, 5] | Roots 0 and 2 (size 2 each): 2 goes under 0 |
| find(3) | [0, 0, 0, 0, 4, 5] | Path 3 → 2 → 0; 3 now points straight at 0 |
| union(4, 5) | [0, 0, 0, 0, 4, 4] | 5 goes under 4 |
| union(5, 3) | [0, 0, 0, 0, 0, 4] | Root 4 (size 2) goes under root 0 (size 4) |
| connected(5, 1) | [0, 0, 0, 0, 0, 0] | find(5) compresses 5 → 4 → 0; both roots are 0: true |
Applications
Kruskal's minimum spanning tree
Minimum Spanning Trees via Kruskal processes edges from lightest to heaviest and keeps an edge only if union(u, v) succeeds, i.e. its endpoints were in different components. Union-find is what makes the cycle check nearly free.
Cycle detection and redundant connections
Add the edges of an undirected graph one at a time. If an edge's endpoints are already connected, that edge closes a cycle. This is the whole solution to Redundant Connection:
def find_redundant_connection(edges: list[list[int]]) -> list[int]:
dsu = DSU(len(edges) + 1) # vertices are labeled 1..n
for u, v in edges:
if not dsu.union(u, v):
return [u, v] # already connected: this edge makes a cycle
return []Dynamic connectivity
When edges arrive over time and connectivity questions are interleaved with them, union-find answers each query in near-constant time, while re-running BFS after every update would cost O(V + E) each time. In Number of Islands II, land cells appear one by one: each new cell starts a new island, and every successful union with a neighboring land cell merges two islands into one.
Grouping by shared attributes
- Accounts Merge: union accounts that share an email; each final root is one person.
- Satisfiability of Equality Equations: union every
a == b, then check that noa != bhas both sides in the same set. - Most Stones Removed: union stones sharing a row or column; the answer is
stones - components. - Number of Operations to Make Network Connected: with enough cables, the answer is
components - 1. - Keys that are not small integers (strings, coordinates) can be mapped to ids with a hash map, or stored directly in a dictionary-based
parent.
Weighted union-find
Store, alongside each parent pointer, a relation between a node and its parent: a ratio, an offset, or a parity bit. find composes these relations along the path while compressing it, so every node ends up holding its relation to the root. Evaluate Division (a / b = 2.0) uses ratios; checking bipartiteness online or "same/different" constraints uses parity.
class WeightedDSU:
"""weight[x] = value(x) / value(parent[x])."""
def __init__(self):
self.parent = {}
self.weight = {}
def add(self, x):
if x not in self.parent:
self.parent[x] = x
self.weight[x] = 1.0
def find(self, x):
if self.parent[x] != x:
root = self.find(self.parent[x])
self.weight[x] *= self.weight[self.parent[x]] # x/p * p/root = x/root
self.parent[x] = root
return self.parent[x]
def union(self, a, b, ratio): # record a / b = ratio
ra, rb = self.find(a), self.find(b)
if ra != rb:
self.parent[ra] = rb
self.weight[ra] = ratio * self.weight[b] / self.weight[a] # ra / rb
def query(self, a, b): # a / b, or -1.0 if unknown
if a not in self.parent or b not in self.parent or self.find(a) != self.find(b):
return -1.0
return self.weight[a] / self.weight[b]Union-find
- Edges arrive incrementally, queries interleaved
- Only needs "same group?" answers, not paths
- Near-constant time per operation
- Cannot remove edges or report paths
BFS / DFS
- The whole graph is known up front
- Can return paths, distances and orders
O(V + E)per full traversal- Re-running after every change is expensive
Complexity
| Variant | find | union | Notes |
|---|---|---|---|
| Naive linking | O(n) | O(n) | Trees can become chains |
| Union by size or rank | O(log n) | O(log n) | Height ≤ log₂ n |
| Path compression only | O(log n) amortized | O(log n) amortized | A single find can still be O(n) |
| Size/rank + compression | O(α(n)) amortized | O(α(n)) amortized | α(n) ≤ 4 for any practical n |
Space is O(n) for the parent and size arrays. union costs two finds plus O(1) linking.
Implementation
The reusable class: `find`, `union` (returns whether a merge happened), `connected`, set sizes and the number of sets.
class DSU:
def __init__(self, n: int) -> None:
self.parent = list(range(n)) # every element starts as its own root
self.size = [1] * n
self.count = n # number of disjoint sets
def find(self, x: int) -> int:
while self.parent[x] != x:
self.parent[x] = self.parent[self.parent[x]] # path halving
x = self.parent[x]
return x
def union(self, a: int, b: int) -> bool:
ra, rb = self.find(a), self.find(b)
if ra == rb:
return False # already in the same set
if self.size[ra] < self.size[rb]:
ra, rb = rb, ra
self.parent[rb] = ra # smaller tree goes under the larger
self.size[ra] += self.size[rb]
self.count -= 1
return True
def connected(self, a: int, b: int) -> bool:
return self.find(a) == self.find(b)
def set_size(self, x: int) -> int:
return self.size[self.find(x)]Key takeaways
- Union-find stores disjoint sets as parent-pointer trees; the root is the set's representative.
- Union by size (or rank) bounds tree height by
log₂ n; path compression or halving flattens trees as you query them. - With both optimizations, operations cost
O(α(n))amortized, andα(n) ≤ 4for any realistic input. unionreturning false is a cycle test, which powers Kruskal's MST and Redundant Connection.- It shines for incremental connectivity with interleaved queries, but cannot delete edges or report paths.
Common pitfalls
- Comparing
parent[a] == parent[b]instead offind(a) == find(b); only roots identify sets. - Linking the original elements instead of their roots (
parent[a] = brather thanparent[find(a)] = find(b)), which corrupts the forest. - Skipping union by size or path compression and getting
O(n)chains on adversarial input. - Recursive full compression on very deep trees in languages with small stacks; path halving is iterative and avoids it.
- Forgetting to decrement the component count only when a union actually merges two different sets.
Interview tips
- Keep a minimal DSU class ready (about 15 lines) and reuse it; interviewers care more about recognizing when to use it.
- Mention both optimizations and the inverse Ackermann bound, then say "effectively constant" so the complexity discussion stays crisp.
- If a problem involves deletions, suggest reversing time so deletions become unions.
Real-world applications
- Kruskal's minimum spanning tree algorithm.
- Network connectivity and incremental clustering.
- Image processing: connected-component labeling of pixels.
- Type inference and unification in compilers (Hindley-Milner).
- Percolation simulations in physics and materials science.
- Merging duplicate records (entity resolution) that share identifiers.
Practice problems
Test yourself
With union by size and path compression together, what is the amortized cost of each operation?
Related topics
Finished this lesson? Track it to see your progress on the roadmap.