Union-find
Track which items belong to the same group as groups merge: near-constant-time union and find with path compression and union by rank.
Description
Union-find answers one question very efficiently: are these two items in the same group?, while groups keep merging. It supports two operations: union(a, b) merges the groups containing a and b, and find(a) returns a representative, the root, of a's group. Two items are connected if they have the same root.
Each group is stored as a tree where every item points to a parent, and the root points to itself. Two simple optimizations make it remarkably fast. Union by rank (or size) always attaches the smaller tree under the larger one, keeping trees shallow. Path compression makes every node on a find path point directly to the root, flattening the tree for next time.
With both, a sequence of operations runs in O(α(n)) each, where α is the inverse Ackermann function: less than 5 for any input that could exist in the universe. In practice, constant time.
Union-find is the engine of Kruskal's minimum spanning tree algorithm, and is used for network connectivity, image segmentation, finding duplicate accounts that share an email or phone number, and percolation simulations.
How it works
Two groups as trees of parent pointers: {A, B, C, D} with root A, and {E, F} with root E
- B → A
- C → A
- D → C
- F → E
Complexity
| Operation | Average | Worst |
|---|---|---|
| Find (with path compression and union by rank)Amortized; α(n) < 5 for any practical n. | O(α(n)) | O(α(n)) |
| Union | O(α(n)) | O(α(n)) |
| Without the optimizations | O(log n) or worse | O(n) |
Space: O(n)
TypeScript implementation
Union-find with path compression and union by size, used to group accounts that share an email or phone number.
// Union-find with path compression and union by size.
export class UnionFind {
private parent: number[];
private size: number[];
groups: number;
constructor(n: number) {
this.parent = Array.from({ length: n }, (_, i) => i);
this.size = new Array(n).fill(1);
this.groups = n;
}
find(x: number): number {
let root = x;
while (this.parent[root] !== root) root = this.parent[root];
while (this.parent[x] !== root) {
const next = this.parent[x];
this.parent[x] = root; // path compression: point straight at the root
x = next;
}
return root;
}
union(a: number, b: number): boolean {
let ra = this.find(a), rb = this.find(b);
if (ra === rb) return false; // already in the same group
if (this.size[ra] < this.size[rb]) [ra, rb] = [rb, ra];
this.parent[rb] = ra; // attach the smaller tree under the larger
this.size[ra] += this.size[rb];
this.groups--;
return true;
}
connected(a: number, b: number): boolean {
return this.find(a) === this.find(b);
}
}
export function demo(): string[] {
// Accounts that share an email or phone number belong to the same person.
const accounts = [
{ id: "acct-1", email: "kim@example.com", phone: "555-0100" },
{ id: "acct-2", email: "kim.l@example.com", phone: "555-0100" },
{ id: "acct-3", email: "kim.l@example.com", phone: "555-0199" },
{ id: "acct-4", email: "sam@example.com", phone: "555-0123" },
{ id: "acct-5", email: "lee@example.com", phone: "555-0177" },
];
const uf = new UnionFind(accounts.length);
const firstSeen = new Map<string, number>();
accounts.forEach((a, i) => {
for (const key of [a.email, a.phone]) {
if (firstSeen.has(key)) uf.union(i, firstSeen.get(key)!);
else firstSeen.set(key, i);
}
});
const people = new Map<number, string[]>();
accounts.forEach((a, i) => people.set(uf.find(i), [...(people.get(uf.find(i)) ?? []), a.id]));
return [
`${accounts.length} accounts belong to ${uf.groups} people`,
...[...people.values()].map((ids) => ` ${ids.join(", ")}`),
`acct-1 and acct-3 are the same person: ${uf.connected(0, 2)}`,
];
}When to use it
Use it when
- Groups merge over time and you repeatedly ask whether two items are connected.
- Kruskal's minimum spanning tree, cycle detection in undirected graphs.
- Clustering and deduplication: linking records that share any identifier.
Avoid it when
- Groups also split: union-find can't undo a union efficiently.
- You need the actual path between two items: use BFS or DFS on a graph.
- The graph is static and you need connectivity once: one BFS or DFS pass is simpler.
Pitfalls
- Skipping the optimizations, which leaves long chains and slow finds.
- Comparing parents instead of roots: two items are connected only if
find(a) === find(b). - Recursive find on huge inputs without path compression, which can overflow the stack.
Alternatives
Breadth-first search
Choose it when the graph is fixed and you need paths or distances, not just connectivity.
Graph
Choose it when you need the edges themselves, not only which component each vertex is in.