Skip to content
ΣDSA Patterns
Menu
Language

Union Find

Guide 2 of 6 · Path 2 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
01234

need 4 edges and 1 component

Graph valid tree: n=5 nodes, edges [0-1, 0-2, 0-3, 1-4]. A tree is connected and acyclic, so it has exactly n-1 edges.

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

Graph Valid Tree

Problem (restated)

n nodes labeled 0..n-1 and undirected edges. Return true if they form a valid tree (connected, acyclic).

Intuition

A tree on n nodes has exactly n-1 edges and is connected. Union-Find rejects any edge that merges already-united nodes (cycle).

Approaches

Union-Find + edge count

Unverified
Time O(n)Space O(n)

Idea. If edges.length != n-1 fail. Union each edge; return false on redundant link. With n-1 successful unions the graph is connected.

Walkthrough. n=5, edges=[[0,1],[0,2],[0,3],[1,4]] → true; adding [1,2] would cycle.

Trade-offs. BFS/DFS from 0 also works; UF is O(α(n)) per op.

Solution
export function validTree(n: number, edges: number[][]): boolean {
  if (edges.length !== n - 1) return false;
  const parent = Array.from({ length: n }, (_, i) => i);
  const find = (x: number): number => {
    while (parent[x] !== x) {
      parent[x] = parent[parent[x]!]!;
      x = parent[x]!;
    }
    return x;
  };
  for (const e of edges) {
    const a = find(e[0]!), b = find(e[1]!);
    if (a === b) return false;
    parent[b] = a;
  }
  return true;
}
export function validTree(n: number, edges: number[][]): boolean {
  if (edges.length !== n - 1) return false;
  const parent = Array.from({ length: n }, (_, i) => i);
  const find = (x: number): number => {
    while (parent[x] !== x) {
      parent[x] = parent[parent[x]!]!;
      x = parent[x]!;
    }
    return x;
  };
  for (const e of edges) {
    const a = find(e[0]!), b = find(e[1]!);
    if (a === b) return false;
    parent[b] = a;
  }
  return true;
}

Template connection

Union-Find for cycle detection + connectivity.

Reflection