Pattern #19
Union Find
AdvancedDynamic connectivity: merge components and query same-set fast.
When to use
Online unions of elements and frequent 'are a and b connected?' queries, or counting components after merges.
Recognition cues
- Number of provinces / graph valid tree
- Accounts merge / redundant connection
- Union by rank + path compression
Common pitfalls
- Forgetting path compression or union by rank (slow chains)
- 1-index vs 0-index parents
- Unioning without checking already-connected (miss cycle detection)
90-second recognition drill
Which pattern fits best?
- Number of provinces / graph valid tree
- Accounts merge / redundant connection
- Union by rank + path compression
Interactive
Mental model
A full worked walkthrough of the invariant. Pause, scrub the dots, or use ← →. Aim to narrate each step yourself.
Step 1 of 8
Statecomponents=5
components = 5
How to think about it
Each element points to a parent; roots represent components. find flattens paths; union links roots (by rank/size). If find(a)==find(b) before union, adding the edge would create a cycle.
Template shapes
| Shape | Core move | Example |
|---|---|---|
| Provinces | Union i and j when the matrix cell is 1. The number of roots is the number of provinces |
LC 547 |
| Valid tree | A tree on n nodes has n - 1 edges and no cycle. A shared root is a cycle. n - 1 successful unions means the graph is connected |
LC 261 |
| Online land | A new land cell unions with land neighbors in the four directions. The component count after each addition is that answer entry | LC 305 |
| Redundant edge | Scan edges in input order. The first edge whose ends already share a root is the redundant one | LC 684 |
| Accounts | Union accounts that share an email. Group the emails by root, sort each group, and put that root’s account name in front | LC 721 |
| Islands | The published write-up marks each island with DFS. The union-find shape of the same grid unions a land cell with its land neighbors and counts roots. That is not the approach on the page | LC 200 |
Complexity baseline
Nearly O(α(n)) per op with path compression + union by rank. Space O(n).
From template to problem
findcompresses the path.unionlinks roots. A shared root means the edge is a cycle (LC 261, LC 684).- Count roots or successful unions.
n - 1successful unions onn - 1edges means a tree (LC 261). Provinces are the root count after every matrix 1 is unioned (LC 547). - Online land unions the four neighbors and appends the count after each new cell (LC 305).
- Accounts group emails by root, sort them, and put the root’s account name first (LC 721). LC 200’s published page is a flood fill.
Template
Same skeleton in TypeScript, Python, and C#. Adapt the invariant; keep the structure.
Union Find · Template
/** Union-Find template: path compression + union by rank. */
export class UnionFind {
parent: number[];
rank: number[];
components: number;
constructor(n: number) {
this.parent = Array.from({ length: n }, (_, i) => i);
this.rank = new Array(n).fill(0);
this.components = n;
}
find(x: number): number {
if (this.parent[x] !== x) this.parent[x] = this.find(this.parent[x]!);
return this.parent[x]!;
}
union(a: number, b: number): boolean {
let ra = this.find(a), rb = this.find(b);
if (ra === rb) return false;
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]!++;
this.components--;
return true;
}
}
/** Union-Find template: path compression + union by rank. */
export class UnionFind {
parent: number[];
rank: number[];
components: number;
constructor(n: number) {
this.parent = Array.from({ length: n }, (_, i) => i);
this.rank = new Array(n).fill(0);
this.components = n;
}
find(x: number): number {
if (this.parent[x] !== x) this.parent[x] = this.find(this.parent[x]!);
return this.parent[x]!;
}
union(a: number, b: number): boolean {
let ra = this.find(a), rb = this.find(b);
if (ra === rb) return false;
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]!++;
this.components--;
return true;
}
}
#StatusProblemTypeDifficultyDone
- 1#200 Number of IslandsGuidemedium
- 2#261 Graph Valid TreeGuidemedium
- 3#305 Number of Islands IIGuidehard
- 4#547 Number of ProvincesGuidemedium
- 5#684 Redundant ConnectionGuidemedium
- 6#721 Accounts MergeGuidemedium