Union-Find
Track which elements belong to the same connected component with near-O(1) union and find operations. Union-Find powers Kruskal's MST, cycle detection in graphs, and dynamic connectivity queries.
What is union-find?
Union-find (disjoint set union) tracks which items belong to the same group. find(x) returns a group's representative and union(a, b) merges two groups. With path compression and union by rank, both run in near-constant time. It answers "are these connected?" questions: network connectivity, Kruskal's minimum spanning tree and detecting cycles in undirected graphs.
class UnionFind {
constructor(n) { this.parent = [...Array(n).keys()]; this.rank = Array(n).fill(0); }
find(x) { return this.parent[x] === x ? x : (this.parent[x] = this.find(this.parent[x])); } // path compression
union(a, b) {
let ra = this.find(a), rb = this.find(b);
if (ra === rb) return false; // already connected
if (this.rank[ra] < this.rank[rb]) [ra, rb] = [rb, ra];
this.parent[rb] = ra;
if (this.rank[ra] === this.rank[rb]) this.rank[ra]++;
return true;
}
}Union and path compression — animated
// Array state
// Pseudocode
Two key optimizations
Core idea — forest of trees
Each element starts as its own root. Union joins two trees by attaching one root to another. Find returns the root of an element's tree — same root means same component.
Full pseudocode
1// Union-Find with path compression + union by rank2class UnionFind:3 parent = [0..n] // parent[i] = i initially (each own root)4 rank = [0..n] // tree height estimate56 function find(x): // path compression7 if parent[x] != x:8 parent[x] = find(parent[x]) // compress: point directly to root9 return parent[x]1011 function union(x, y): // union by rank12 rx = find(x) ry = find(y)13 if rx == ry: return false // already connected14 if rank[rx] < rank[ry]: swap(rx, ry)15 parent[ry] = rx // attach shorter tree under taller16 if rank[rx] == rank[ry]: rank[rx]++17 return true
Complexity
O(α(n)) time
O(α(n)) time
Linear time
🎯 Quick Check
After path compression, find(x) is called again on the same x. What is its time complexity now?
Union-Find (Disjoint Set): summary
Key points
- Amortized time is O(α(n)), the inverse Ackermann function, which is under 5 for any realistic n.
unionreturning false means the edge would create a cycle.
Frequently asked questions
›When should I use union-find instead of BFS or DFS?
When connections are added incrementally and you repeatedly ask whether two items are connected. Union-find answers each query almost instantly without re-traversing.