Skip to content
ΣDSA Patterns
Menu
Language

Union Find

Guide 4 of 6 · Path 4 of 6

Interactive

Mental model

A worked animation for this problem. Scrub steps or press space to pause; re-tell the invariant out loud.

Step 1 of 6
012

isConnected 3×3

Number of provinces. 3 cities, 0—1 connected, 2 alone. Count connected components.

Demo preview: These solutions pass the automated test suite but have not been human-reviewed. Treat trade-offs and prose as draft.

Number of Provinces

Problem (restated)

n cities with isConnected matrix. A province is a connected group. Return number of provinces.

Intuition

Union connected pairs; answer is component count.

Approaches

Union-Find

Unverified
Time O(n² α(n))Space O(n)

Idea. UF on i-j when matrix[i][j]==1.

Walkthrough. Fully connected → 1 province.

Trade-offs. UF vs DFS flood on matrix.

Solution
export function findCircleNum(isConnected: number[][]): number {
  const n = isConnected.length;
  const p = Array.from({ length: n }, (_, i) => i);
  const find = (x: number): number => (p[x] === x ? x : (p[x] = find(p[x]!)));
  let comp = n;
  for (let i = 0; i < n; i++) {
    for (let j = i + 1; j < n; j++) {
      if (isConnected[i]![j] === 1) {
        const a = find(i), b = find(j);
        if (a !== b) {
          p[b] = a;
          comp--;
        }
      }
    }
  }
  return comp;
}
export function findCircleNum(isConnected: number[][]): number {
  const n = isConnected.length;
  const p = Array.from({ length: n }, (_, i) => i);
  const find = (x: number): number => (p[x] === x ? x : (p[x] = find(p[x]!)));
  let comp = n;
  for (let i = 0; i < n; i++) {
    for (let j = i + 1; j < n; j++) {
      if (isConnected[i]![j] === 1) {
        const a = find(i), b = find(j);
        if (a !== b) {
          p[b] = a;
          comp--;
        }
      }
    }
  }
  return comp;
}

Template connection

Union-Find components.

Reflection