Union-find
medium 20 minUnion-find, also called a disjoint set union (DSU), keeps elements split into non-overlapping groups.
Chapter mnemonic
Two Union-Find optimizations
Small hill joins tall hill. Trail signs point to the summit.
Which optimization changes signposts along an existing path?
Path compression redirects visited nodes toward the root. Union by rank guides the merge of two trees.
Video lesson · Chapter 1 of 7
Radio crews reconnect
Union-find in 75 seconds
1:20Reel
How it works
Step through the idea, or press Play.
Store one parent per element. parent[i] = i means i is a root. Every group is a tree, and its root is the group's name
Understand it
Start here
Groups with leaders
Quick recap
Graphs
Vertices joined by edges. A connected component is a maximal set of vertices that can all reach each other. Basics in graphs intro.
Trees
A rooted tree has one root and every other node has exactly one parent. That single parent pointer is all union-find stores.
Amortised cost
The average cost per operation over a long sequence, even if a few single operations are slow.
Union-find tracks elements split into disjoint (non-overlapping) sets. Think of teams with leaders. Find asks "who is the leader of x's team?" and union merges two teams under one leader. Two elements are in the same team exactly when they have the same leader. It answers "are these two connected?" while edges keep arriving, which BFS and DFS cannot do cheaply.
The idea
Two operations: find and union
find(x)
Follow parent pointers from x until a node is its own parent. That root names the set. amortised.
union(a, b)
Find both roots. If they differ, point one root at the other and return True; if they match, return False. amortised.
connected(a, b)
Just
find(a) == find(b). Same root means same set.count
Start at and subtract one on every union that returns True. That is the number of sets, or connected components.
- 1FindWho is the boss of a? Of b?
- 2CompareSame boss: nothing to do
- 3MergeSmaller team joins the bigger one
- 4CompressEveryone visited now points at the boss
Find who is the boss, then merge the teams. Skip the middlemen and let the big fish eat the small fish.
Representation
The parent array and the forest
The entire structure is one array: parent[i] is i's parent, and a root points to itself. Read as a picture, the array is a forest: one tree per set, with an arrow from every element up to its parent. The second array, rank, is only consulted at roots.
Before and after union(2, 4)
| Element | 0 | 1 | 2 | 3 | 4 |
|---|---|---|---|---|---|
parent before | 0 | 0 | 0 | 3 | 3 |
parent after | 0 | 0 | 0 | 0 | 3 |
The same sets as a forest
Operation 1
find with path compression
find with path compression
Take the chain 4 → 3 → 2 → 1 → 0. The first find(4) walks all four hops and finds root 0. While the recursion unwinds it sets parent[1], parent[2], parent[3] and parent[4] to 0, so the chain becomes a star. Every later find on those nodes is one hop. The heart of it is one line: parent[x] = find(parent[x]).
parent = [0, 0, 1, 2, 3] # chain 4 -> 3 -> 2 -> 1 -> 0def find(x): if parent[x] != x: parent[x] = find(parent[x]) # path compression return parent[x]print(find(4), parent) # 0 [0, 0, 0, 0, 0]def find_halving(x): while parent[x] != x: parent[x] = parent[parent[x]] # skip every other node x = parent[x] return xparent = [0, 0, 1, 2, 3]print(find_halving(4), parent) # 0 [0, 0, 0, 2, 2]Operation 2
union by rank or by size
union by rank
If you always hang the first root under the second, a bad order of unions builds a chain of height , and find becomes . Union by rank hangs the shorter tree under the taller one, where rank is an upper bound on height. Union by size hangs the smaller set under the larger one. Either keeps every tree shallow.
Why rank keeps trees shallow
Rank or size?
| Union by rank | Union by size | |
|---|---|---|
| Stores | upper bound on height | number of elements in the set |
| Link rule | lower rank under higher | smaller set under larger |
| Grows | by 1, only on a tie | by the other set's size, every union |
| Bonus | rank fits in a byte | the size of any set for free: size[find(x)] |
| Guarantee | height | height |
Complexity
Why it is nearly O(1)
Cost per operation
| Version | find | m operations |
|---|---|---|
| Naive linking | worst case | |
| Union by rank only | worst case | |
| Path compression only | amortised | |
| Both | amortised |
parent and rank arrays in every version.The inverse Ackermann function
Application 1
Cycle detection in undirected graphs
Add the edges one at a time. Before adding , ask whether and are already connected. If find(u) == find(v), a path between them already exists, and the new edge would close a loop. Otherwise union them and continue. This is exactly the test Kruskal's algorithm uses to reject an edge.
Cycle check, edge by edge
A counting view
Application 2
Connected components and number of provinces
Cities are connected directly or through other cities; a province is a group of cities that can all reach each other, which is a connected component. Start with sets and union the two ends of every connection. Each union that returns True merges two provinces into one.
Components by subtraction
def count_provinces(is_connected): n = len(is_connected) parent = list(range(n)) def find(x): while parent[x] != x: parent[x] = parent[parent[x]] x = parent[x] return x count = n for i in range(n): for j in range(i + 1, n): if is_connected[i][j]: ri, rj = find(i), find(j) if ri != rj: parent[rj] = ri count -= 1 return countprint(count_provinces([[1, 1, 0], [1, 1, 0], [0, 0, 1]])) # 2print(count_provinces([[1, 0, 0], [0, 1, 0], [0, 0, 1]])) # 3Application 3
Redundant connection
A tree on nodes had one extra edge added, so the graph has exactly one cycle. Which edge can you remove to get a tree back? Run the cycle check: the first edge whose union returns False is the answer. Because the edges before it formed a forest, it is the edge that appears last among the cycle's edges in the input.
Edges [1, 2], [2, 3], [3, 4], [1, 4], [1, 5]
| Edge | find(u) | find(v) | Verdict |
|---|---|---|---|
| [1, 2] | 1 | 2 | union, set {1, 2} |
| [2, 3] | 1 | 3 | union, set {1, 2, 3} |
| [3, 4] | 1 | 4 | union, set {1, 2, 3, 4} |
| [1, 4] | 1 | 1 | same root: redundant |
| [1, 5] | never reached |
Application 4
Accounts merge: union-find on labels
Each account is a name followed by emails. Two accounts belong to the same person if they share any email, and sharing is transitive. Treat every email as an element. Within one account, union every email with that account's first email. When all accounts are processed, the emails that share a root belong to one person; group them by root, sort them, and attach the name.
Accounts merge
Choosing
Union-find vs DFS/BFS
Reach for union-find when
- Edges arrive over time and connectivity is asked in between.
- You only need "same group or not" and the number or size of groups.
- You are building an MST with Kruskal or detecting the edge that closes a cycle.
- Elements are labels (emails, accounts) that merge by shared keys.
Use DFS or BFS instead when
- You need the actual path, the distance, or the order of visits.
- The graph is directed: union-find cannot see direction.
- Edges are deleted: union-find cannot split a set.
- The graph is static and you only need one pass: traversal is simpler.
Which tool?
Side by side
| Union-find | DFS / BFS | |
|---|---|---|
| Add an edge | rebuild or re-search, | |
| Connected query | per query, or after labelling a static graph | |
| Path between two nodes | not available | yes |
| Directed graphs | no | yes |
| Extra space | adjacency plus visited |
Wrap-up
The full structure and what to remember
class UnionFind: def __init__(self, n): self.parent = list(range(n)) self.rank = [0] * n self.size = [1] * n self.count = n def find(self, x): if self.parent[x] != x: self.parent[x] = self.find(self.parent[x]) return self.parent[x] def union(self, a, b): ra, rb = self.find(a), self.find(b) if ra == rb: return False if self.rank[ra] < self.rank[rb]: ra, rb = rb, ra self.parent[rb] = ra self.size[ra] += self.size[rb] if self.rank[ra] == self.rank[rb]: self.rank[ra] += 1 self.count -= 1 return Trueuf = UnionFind(6)for a, b in [(0, 1), (0, 2), (3, 4), (2, 4)]: uf.union(a, b)print(uf.count, uf.size[uf.find(4)], uf.union(1, 3)) # 2 5 FalseKey points
- Union-find keeps disjoint sets as trees in one parent array; a root has
parent[x] == xand names its set. - find follows parents to the root; path compression re-points every visited node at the root.
- union links root to root, the shorter tree under the taller (rank) or the smaller set under the larger (size).
- Rank alone bounds height by log₂ n; together with compression, m operations cost O(m α(n)), effectively constant each.
- union returning False means the two ends were already connected: a cycle in an undirected graph, or a redundant edge.
- Components = n minus the successful unions, which solves number of provinces and number of islands.
- Use a dictionary as the parent map to merge labels such as emails in accounts merge.
- Prefer DFS/BFS for paths, distances, directed graphs or deletions; prefer union-find when edges arrive over time.