Union-find
medium 20 minUnion-find, also called a disjoint set union (DSU), keeps elements split into non-overlapping groups.
See it run
Every element points to a parent, every set is a tree with one root, and find and union keep those trees almost flat.
Operations
Parent array
The old execution example: four elements, three unions and one find, read straight off the parent and rank arrays.
Step 1 of 8
Every element is its own root
parent
- 00
- 11
- 22
- 33
rank
- 00
- 01
- 02
- 03
UnionFind(4) sets parent[i] = i for every index, so each element is a root and a set of one. Every rank is 0 and there are 4 sets. Roots are shown in mint.
Step 1: Every element is its own root
class UnionFind: def __init__(self, n): self.parent = list(range(n)) # every element is its own root self.rank = [0] * n # upper bound on each tree's height self.count = n # number of disjoint sets def find(self, x): if self.parent[x] != x: self.parent[x] = self.find(self.parent[x]) # path compression return self.parent[x] def union(self, a, b): ra, rb = self.find(a), self.find(b) if ra == rb: return False # already in the same set if self.rank[ra] < self.rank[rb]: ra, rb = rb, ra # make ra the taller root self.parent[rb] = ra # hang the shorter tree under it if self.rank[ra] == self.rank[rb]: self.rank[ra] += 1 # equal heights: the tree grew by one self.count -= 1 return True def connected(self, a, b): return self.find(a) == self.find(b)uf = UnionFind(4)uf.union(0, 1) # parent [0, 0, 2, 3]uf.union(2, 3) # parent [0, 0, 2, 2]uf.union(1, 3) # parent [0, 0, 0, 2]print(uf.find(3)) # 0, and parent[3] becomes 0print(uf.parent, uf.rank, uf.count)# [0, 0, 0, 0] [2, 0, 1, 0] 1- Time
- O(α(n)) amortised
- Space
- O(n)
- storage
- two int arrays of size n
- root test
- parent[x] == x
The parent array is the whole data structure. A root is any i with parent[i] == i, and two elements share a set exactly when they reach the same root.
In the real world
The same union-find doing real jobs. Pick one and step through it.
Six computers, cables added one at a time. Are two machines on the same network, and how many separate networks are there?
Step 1 of 5
Six machines, six networks
networks
6
No cables yet. Each computer is its own network, labelled with its root, and count = 6.
Step 1: Six machines, six networks
uf = UnionFind(6) # the class from the methods abovefor a, b in [(0, 1), (1, 2), (3, 4)]: uf.union(a, b)print(uf.connected(0, 2), uf.connected(0, 4), uf.count) # True False 3uf.union(2, 4)print(uf.connected(0, 4), uf.count) # True 2Common mistakes
The bugs interviewers watch for, with the fix beside each.
Comparing parents instead of roots
criticalparent[x] is only the next hop. In the parent array [0, 0, 0, 2], elements 1 and 3 have parents 0 and 2 but share root 0, so a parent comparison says they are apart when they are together.
Wrongdef connected(a, b): return parent[a] == parent[b]Rightdef connected(a, b): return find(a) == find(b)Linking the elements instead of their roots
criticalSetting parent[a] = b cuts a out of its old tree and leaves the rest of a's set behind under the old root, so the two sets never really merge.
Wrongdef union(a, b): parent[a] = bRightdef union(a, b): ra, rb = find(a), find(b) if ra != rb: parent[rb] = raCalling find without storing the result
majorThe recursion reaches the root but nothing is rewritten, so there is no path compression and long chains stay long.
Wrongdef find(x): if parent[x] != x: return find(parent[x]) return xRightdef find(x): if parent[x] != x: parent[x] = find(parent[x]) # store it: this is the compression return parent[x]Raising the rank on every union
majorRank must grow only when two equal ranks meet. Bumping it every time, or hanging the taller tree under the shorter one, throws away the log n height guarantee.
Wrongparent[rb] = rarank[ra] += 1Rightif rank[ra] < rank[rb]: ra, rb = rb, raparent[rb] = raif rank[ra] == rank[rb]: rank[ra] += 1Deep recursion in Python
minorBefore the first compression a chain can be thousands of nodes long, and recursive find then hits Python's recursion limit. An iterative find with path halving has the same amortised cost and no recursion.
Wrongdef find(x): if parent[x] != x: parent[x] = find(parent[x]) return parent[x] # RecursionError on a 10**5 chainRightdef find(x): while parent[x] != x: parent[x] = parent[parent[x]] # path halving x = parent[x] return xUsing union-find on directed edges
majorUnion-find forgets direction. The edges 1 → 2, 1 → 3, 2 → 3 make no directed cycle, yet the third edge joins two nodes that already share a root.
Wrongfor u, v in directed_edges: if not union(u, v): return True # wrong for directed graphsRight# directed graph: DFS with three colours,# or Kahn's topological sort (cycle if not all nodes come out)
Interview tips
How to explain it
- Each set is a tree stored in a parent array; the root names the set.
- find follows parents to the root and compresses the path; union links the shorter root under the taller one.
- With both tricks, m operations cost O(m α(n)): effectively constant each. Space O(n).
Spot the pattern
- Groups that only ever merge, never split.
- "Are these two connected?" asked many times while edges keep arriving.
- Count components, find the edge that closes a cycle, or merge records that share a key.
Memory trick: FIND & MERGE
- Find: who is the boss? Follow parents to the root.
- Merge: two teams join under one boss.
- Skip the middlemen (path compression); big fish eats small fish (union by rank).
Union-find or DFS/BFS?
- Static graph, one pass, or you need the actual path: DFS or BFS.
- Edges arrive over time with connectivity queries in between: union-find.
- Directed graphs or deletions: not union-find.