Union-Find (Disjoint Set Union)
Track which elements are connected, merging groups in nearly O(1) — with path compression and union by rank.
Union-Find (also called Disjoint Set Union, DSU) maintains a collection of non-overlapping sets and supports two operations:
- find(x) — which set is x in? (returns a representative "root")
- union(x, y) — merge the sets containing x and y.
It answers "are these two things connected?" while connections are being added — far faster than re-running BFS each time.
The idea: a forest of parent pointers
Each set is a tree; each element points to its parent; the root represents the set. Initially everyone is their own root.
Two optimisations make it extremely fast:
- Path compression — during
find, point every visited node directly at the root, flattening the tree. - Union by rank / size — attach the shorter (or smaller) tree under the taller one, so trees stay shallow.
With both, any sequence of m operations costs O(m · α(n)), where α is the inverse Ackermann function — at most 4 for any n that fits in the universe. Effectively O(1) per operation.
class DSU {
private final int[] parent, size;
private int components;
DSU(int n) {
parent = new int[n];
size = new int[n];
components = n;
for (int i = 0; i < n; i++) { parent[i] = i; size[i] = 1; }
}
int find(int x) {
if (parent[x] != x) parent[x] = find(parent[x]); // path compression
return parent[x];
}
boolean union(int a, int b) {
int ra = find(a), rb = find(b);
if (ra == rb) return false; // already connected
if (size[ra] < size[rb]) { int t = ra; ra = rb; rb = t; }
parent[rb] = ra; // union by size
size[ra] += size[rb];
components--;
return true;
}
boolean connected(int a, int b) { return find(a) == find(b); }
int count() { return components; }
}class DSU:
def __init__(self, n: int):
self.parent = list(range(n))
self.size = [1] * n
self.components = n
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
if self.size[ra] < self.size[rb]:
ra, rb = rb, ra
self.parent[rb] = ra # union by size
self.size[ra] += self.size[rb]
self.components -= 1
return Trueclass DSU {
parent: number[];
size: number[];
components: number;
constructor(n: number) {
this.parent = Array.from({ length: n }, (_, i) => i);
this.size = new Array(n).fill(1);
this.components = n;
}
find(x: number): number {
while (this.parent[x] !== x) {
this.parent[x] = this.parent[this.parent[x]]; // path halving
x = this.parent[x];
}
return x;
}
union(a: number, b: number): boolean {
let ra = this.find(a), rb = this.find(b);
if (ra === rb) return false;
if (this.size[ra] < this.size[rb]) [ra, rb] = [rb, ra];
this.parent[rb] = ra; // union by size
this.size[ra] += this.size[rb];
this.components--;
return true;
}
}Where Union-Find shines
- Kruskal's MST — add edges cheapest-first, skipping any that would join an already-connected pair. See MST.
- Cycle detection in undirected graphs —
unionreturning false means the edge closes a cycle ("Redundant Connection"). - Number of connected components / provinces as edges arrive.
- Grouping by equivalence — accounts merge (same email), similar strings, equations
a == b. - Percolation and image segmentation.
- DSU supports find and union over disjoint sets.
- Path compression + union by rank/size ⇒ amortized near-O(1), technically O(α(n)).
- Ideal for incremental connectivity, Kruskal, cycle detection and grouping problems.
QWhy does each optimisation alone give O(log n), but both together O(α(n))?hard
Union by rank alone keeps tree height ≤ log n. Path compression alone gives O(log n) amortized. Combined, Tarjan proved the amortized bound O(α(n)) — the inverse Ackermann function, which grows so slowly it is at most 4 for any practical n.
QAccounts merge: merge accounts that share any email.medium
Map each email to an id; for each account, union all its emails with the first one. Then group emails by find(email), sort each group and attach the owner's name. O(n α(n) + sorting).