Skip to content
DSA Patterns
Menu
Language

Pattern #19

Union Find

Advanced

Dynamic 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
1/8

Five elements; each is its own parent.

0r=01r=02r=03r=04r=0
Statecomponents=5

components = 5

Key:CurrentActive rangeMatchSettled

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

  1. find compresses the path. union links roots. A shared root means the edge is a cycle (LC 261, LC 684).
  2. Count roots or successful unions. n - 1 successful unions on n - 1 edges means a tree (LC 261). Provinces are the root count after every matrix 1 is unioned (LC 547).
  3. Online land unions the four neighbors and appends the count after each new cell (LC 305).
  4. 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;
  }
}
#StatusProblemTypeDone
  1. 1#200 Number of IslandsGuide
  2. 2#261 Graph Valid TreeGuide
  3. 3#305 Number of Islands IIGuide
  4. 4#547 Number of ProvincesGuide
  5. 5#684 Redundant ConnectionGuide
  6. 6#721 Accounts MergeGuide