Disjoint Set / Union-Find (DSA #17)
A social network adds friendships one at a time and keeps asking “are these two people in the same friend group?” You cannot re-run a graph traversal after every edge without wasting time, and the groups keep merging. Union-Find (the disjoint-set data structure) answers exactly this: it tracks a partition of elements into groups, supports “merge two groups” and “are these two in the same group?”, and does both in nearly constant time. It is the engine behind Kruskal’s MST, cycle detection, and a long list of “connected components” problems.
This chapter covers the parent-array representation, path compression, union by rank, and the problems where Union-Find is the cleanest tool.
The representation: a forest of parent pointers
Each element points to a parent; following parents reaches a representative (root) that names the set. An element is its own root if it is a representative.
class UnionFind:
def __init__(self, n):
self.parent = list(range(n)) # each element starts alone
self.rank = [0] * n # tree height bound
def find(self, x):
while self.parent[x] != x:
x = self.parent[x]
return x
Two elements are connected iff they share a root: find(a) == find(b).
\begin{tikzpicture}[font=\rmfamily, >=stealth,
n/.style={draw, thick, circle, minimum size=0.62cm, font=\small\bfseries, inner sep=0pt},
a/.style={->, thick}]
\node[n, fill=orange!28] (r1) at (0,0) {0};
\node[n, fill=blue!12] (c1) at (-0.9,-1.0) {2};
\node[n, fill=blue!12] (c2) at (0.9,-1.0) {3};
\node[n, fill=green!16] (gc) at (-1.3,-2.0) {5};
\draw[a] (c1) -- (r1); \draw[a] (c2) -- (r1); \draw[a] (gc) -- (c1);
\node[font=\rmfamily\small, text=black!60, anchor=north] at (0,-2.5) {parent pointers form a forest; the root is the set's id};
\end{tikzpicture}
Union: attach one root under another
To merge two sets, find both roots and make one the parent of the other.
def union(self, a, b):
ra, rb = self.find(a), self.find(b)
if ra == rb:
return False # already connected (cycle!)
self.parent[ra] = rb # naive: one root points to the other
return True
union returning False when the two are already connected is exactly how you detect a cycle while adding edges to an undirected graph (used by Kruskal).
Optimization 1: union by rank
Naive union can build a long chain. Union by rank always attaches the shorter tree under the taller one, keeping height \(O(\log n)\).
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
if self.rank[ra] == self.rank[rb]:
self.rank[ra] += 1
return True
\begin{tikzpicture}[font=\rmfamily, >=stealth,
n/.style={draw, thick, circle, minimum size=0.58cm, font=\small\bfseries, inner sep=0pt},
a/.style={->, thick}]
\node[n, fill=orange!28] (r1) at (-2.4,0) {0};
\node[n, fill=blue!12] (c1) at (-3.0,-0.9) {1};
\node[n, fill=blue!12] (c2) at (-1.8,-0.9) {2};
\node[n, fill=green!25] (r2) at (1.2,0) {3};
\draw[a] (c1) -- (r1); \draw[a] (c2) -- (r1);
\draw[a, thick, red!60] (r1) -- (r2);
\node[font=\rmfamily\small, text=black!60, anchor=north] at (0,-1.5) {shorter tree hangs under taller root: rank 1 under rank 2};
\end{tikzpicture}
Optimization 2: path compression
Every find can flatten the path by pointing visited nodes directly at the root. Subsequent finds become nearly instant.
def find(self, x):
root = x
while self.parent[root] != root: # 1. find the root
root = self.parent[root]
while self.parent[x] != root: # 2. re-point everything to it
self.parent[x], x = root, self.parent[x]
return root
The recursive one-liner is elegant but uses stack space; the iterative two-pass version above is what you want for large inputs.
\begin{tikzpicture}[font=\rmfamily, >=stealth,
n/.style={draw, thick, circle, minimum size=0.58cm, font=\small\bfseries, inner sep=0pt},
a/.style={->, thick}]
\node[n, fill=orange!28] (r) at (0,0) {0};
\node[n, fill=blue!12] (a2) at (-1.4,-1.0) {2};
\node[n, fill=blue!12] (a5) at (-2.2,-2.0) {5};
\draw[a, dashed, red!60] (a5) to[bend right=20] (r);
\node[font=\rmfamily\small, text=black!60, anchor=west] at (0.4,-1.5) {after find(5): 5 points straight at 0};
\end{tikzpicture}
The complexity
Union by rank alone gives \(O(\log n)\). Path compression alone gives amortized \(O(\log n)\). Together they give amortized \(O(\alpha(n))\) — the inverse Ackermann function, which is below 5 for any input that fits in the observable universe. For all practical purposes, Union-Find is constant time per operation.
| Variant | find (amortized) |
|---|---|
| naive | \(O(n)\) |
| union by rank only | \(O(\log n)\) |
| path compression only | \(O(\log n)\) amortized |
| both | \(O(\alpha(n)) \approx O(1)\) |
Where Union-Find is the right tool
- Connected components in an undirected graph, added incrementally.
- Cycle detection while building a graph (especially Kruskal’s MST, Chapter 22).
- Number of provinces / friend circles — count distinct roots.
- Accounts merge — union emails that belong to the same person, then group.
- Grid connectivity — union adjacent land cells, or query whether two cells connect.
- Dynamic equivalence — compilers, image segmentation, percolation.
# number of connected components after a list of undirected edges
def count_components(n, edges):
uf = UnionFind(n)
for u, v in edges:
uf.union(u, v)
return len({uf.find(i) for i in range(n)})
For static connectivity (no new edges), a single BFS/DFS is simpler. Union-Find shines when edges arrive over time or when merges are interleaved with connectivity queries.
Pitfalls
- Forgetting path compression or union by rank. Naive Union-Find degrades to \(O(n)\) per find on adversarial inputs.
- Comparing elements instead of roots. Always compare
find(a) == find(b), neverparent[a] == parent[b]. - Recursive
findon a long chain. It can overflow the stack; use the iterative two-pass version. - Using Union-Find for top-down searches. It answers connectivity, not path or distance; use BFS/DFS when you need the route.
- Deleting from a set. Union-Find only merges; it does not support splitting. For dynamic deletion, use another structure.
What do union by rank and path compression each buy, and what is the combined complexity? Why does union returning False mean a cycle?
ASolution
Union by rank keeps trees shallow by attaching shorter under taller; path compression flattens paths during find. Together they give amortized \(O(\alpha(n))\), effectively constant. If union(a, b) finds both already sharing a root, adding edge (a, b) would close a loop, so it signals a cycle.
Next: Suffix Trees and Arrays (DSA #18) — finding substrings and repeats in linear-ish time.