Groups that merge
Imagine every person in a company has a “my boss is…” note. To find out which department someone is in, you follow the notes up until you reach someone whose note says “myself”: the head of the department. That person represents the whole group.
Union-Find works exactly like that:
parentis an array:parent[i]is the elementipoints to. At the start, everyone points to themselves: every element is its own group.find(x)follows parents fromxup to the root (an element that points to itself). Two elements are in the same group if they have the same root.union(a, b)finds both roots and makes one of them point to the other. Now both groups have one root, so they’re one group.
Two small tricks keep the chains short, so find stays fast:
- Union by size: attach the smaller group under the larger one, so trees stay shallow.
- Path compression: after
find(x)reaches the root, make every element on the way point directly at the root. The nextfindis one step.
The structure is a forest stored in a parent array; a root identifies its set. find follows parent links to the root; union links one root under the other. With union by size (or rank) alone, trees have height O(log n); with path compression alone, amortized cost is O(log n); with both, the amortized cost per operation is O(α(n)), the inverse Ackermann function, which is at most 4 for any input that fits in the universe. Iterative compression (two passes, or path halving parent[x] = parent[parent[x]]) avoids recursion depth issues. Union-Find handles incremental connectivity only: it can’t delete edges or split sets (that needs offline reverse processing or dynamic connectivity structures). Map non-integer items (emails, coordinates) to indices with a hash map, or use a map-based parent.
struct UnionFind {
private var parent: [Int]
private var size: [Int]
private(set) var components: Int
init(_ n: Int) {
parent = Array(0..<n) // everyone starts as their own root
size = Array(repeating: 1, count: n)
components = n
}
mutating func find(_ x: Int) -> Int {
var root = x
while parent[root] != root { root = parent[root] }
var node = x
while parent[node] != root { // path compression
let next = parent[node]
parent[node] = root
node = next
}
return root
}
@discardableResult
mutating func union(_ a: Int, _ b: Int) -> Bool {
var rootA = find(a), rootB = find(b)
if rootA == rootB { return false } // already in the same group
if size[rootA] < size[rootB] { swap(&rootA, &rootB) }
parent[rootB] = rootA // smaller tree under the larger
size[rootA] += size[rootB]
components -= 1
return true
}
}class UnionFind(n: Int) {
private val parent = IntArray(n) { it } // everyone starts as their own root
private val size = IntArray(n) { 1 }
var components = n
private set
fun find(x: Int): Int {
var root = x
while (parent[root] != root) root = parent[root]
var node = x
while (parent[node] != root) { // path compression
val next = parent[node]
parent[node] = root
node = next
}
return root
}
fun union(a: Int, b: Int): Boolean {
var rootA = find(a)
var rootB = find(b)
if (rootA == rootB) return false // already in the same group
if (size[rootA] < size[rootB]) rootA = rootB.also { rootB = rootA }
parent[rootB] = rootA // smaller tree under the larger
size[rootA] += size[rootB]
components--
return true
}
}class UnionFind {
private final int[] parent;
private final int[] size;
private int components;
UnionFind(int n) {
parent = new int[n];
size = new int[n];
for (int i = 0; i < n; i++) { parent[i] = i; size[i] = 1; } // everyone starts as their own root
components = n;
}
int find(int x) {
int root = x;
while (parent[root] != root) root = parent[root];
while (parent[x] != root) { // path compression
int next = parent[x];
parent[x] = root;
x = next;
}
return root;
}
boolean union(int a, int b) {
int rootA = find(a), rootB = find(b);
if (rootA == rootB) return false; // already in the same group
if (size[rootA] < size[rootB]) { int t = rootA; rootA = rootB; rootB = t; }
parent[rootB] = rootA; // smaller tree under the larger
size[rootA] += size[rootB];
components--;
return true;
}
int components() { return components; }
}class UnionFind {
private readonly parent: number[];
private readonly size: number[];
components: number;
constructor(n: number) {
this.parent = Array.from({ length: n }, (_, i) => i); // everyone starts as their own root
this.size = new Array(n).fill(1);
this.components = n;
}
find(x: number): number {
let root = x;
while (this.parent[root] !== root) root = this.parent[root];
while (this.parent[x] !== root) { // path compression
const next = this.parent[x];
this.parent[x] = root;
x = next;
}
return root;
}
union(a: number, b: number): boolean {
let rootA = this.find(a);
let rootB = this.find(b);
if (rootA === rootB) return false; // already in the same group
if (this.size[rootA] < this.size[rootB]) [rootA, rootB] = [rootB, rootA];
this.parent[rootB] = rootA; // smaller tree under the larger
this.size[rootA] += this.size[rootB];
this.components--;
return true;
}
}findfirst walks up to the root, then walks the same path again and points every node straight at the root.unionworks on the two roots. If they’re the same, the elements were already connected, andunionreturnsfalse, which is very useful (next part).componentsstarts atnand drops by one on every successful union, so you always know how many groups there are.
Predict the output
A Union-Find over 5 elements (0 to 4) runs union(0, 1), union(2, 3), union(1, 3). How many components are there, and are 0 and 2 connected?
After union(0, 1) and union(2, 3) there are three groups: {0, 1}, {2, 3}, {4}. union(1, 3) finds the roots of 1 and 3, which are different, and merges the two groups: {0, 1, 2, 3} and {4}. 0 and 2 now have the same root, so they're connected, even though nobody called union(0, 2).
Tap the line with the bug.
mutating func union(_ a: Int, _ b: Int) {
parent[a] = b
components -= 1
}fun union(a: Int, b: Int) {
parent[a] = b
components--
}void union(int a, int b) {
parent[a] = b;
components--;
}union(a: number, b: number): void {
this.parent[a] = b;
this.components--;
}Hint: Run union(0, 1), then union(0, 2). Where does 1 end up?
It links the elements, not their roots. After union(0, 1), 0 points to 1. Then union(0, 2) overwrites 0’s parent with 2: now 0 and 2 are together, but 1 has been cut off, even though 0 and 1 were connected. It also decrements components even when a and b were already in the same group, so the count goes wrong (even negative).
Always find both roots, do nothing if they’re equal, and link root to root:
mutating func union(_ a: Int, _ b: Int) {
let rootA = find(a), rootB = find(b)
if rootA == rootB { return }
parent[rootB] = rootA
components -= 1
}fun union(a: Int, b: Int) {
val rootA = find(a); val rootB = find(b)
if (rootA == rootB) return
parent[rootB] = rootA
components--
}void union(int a, int b) {
int rootA = find(a), rootB = find(b);
if (rootA == rootB) return;
parent[rootB] = rootA;
components--;
}union(a: number, b: number): void {
const rootA = this.find(a), rootB = this.find(b);
if (rootA === rootB) return;
this.parent[rootB] = rootA;
this.components--;
}(Add union by size on top, as in the full version above.)
Why both optimizations matter
Predict the output
A Union-Find without union by size and without path compression always links parent[rootA] = rootB. It runs union(0, 1), union(0, 2), union(0, 3), …, union(0, n − 1). How long does the last find(0) take?
Each union puts 0's current root under the new element: 0 → 1 → 2 → … → n − 1. The tree is a linked list, so find(0) walks n − 1 links, and n such operations cost O(n²). Union by size would always attach the single new element under the big tree (height stays 1); path compression would flatten the chain on the first find. Together they give O(α(n)) amortized.
Deep diveRecursion and stack depthInterview favorite
The textbook path compression is recursive: parent[x] = find(parent[x]). On a degenerate chain of 100,000 nodes (possible when union by size is missing, or before compression has happened), that’s 100,000 nested calls: a StackOverflowError on the JVM, a crash in Swift, RangeError: Maximum call stack size exceeded in JavaScript. The iterative two-pass version in this lesson, or path halving (parent[x] = parent[parent[x]] while walking), has the same complexity with constant stack use, which is what production code should use.
- Forest in a
parentarray; root = set id.findto root;unionlinks roots. - Union by size/rank → O(log n) height; path compression → flattening; both → O(α(n)) amortized (≤ 4 in practice).
- Iterative compression or path halving: no deep recursion on degenerate chains.
unionreturning false = already connected: cycle detection for free. Track component count.- Incremental only: no edge deletion or set splitting. Map arbitrary keys to indices.
Check this part
How do you know two elements are in the same group?
What does union by size do?
What is the amortized cost per operation with both optimizations?
Which operation can Union-Find not support efficiently?