Union-Find

Trees & Graphs

Signal

Connected groups, friend circles, merge accounts

Template

Union elements, count distinct roots; path compression + rank.

Worked example (1)

#15

Union-Find

Union-Find

A tree had one extra edge added, forming a single cycle. Return the edge that can be removed to restore a tree.

class UnionFind {
  private parent: number[];
  private rank: number[];
  constructor(size: number) {
    this.parent = Array.from({ length: size }, (_, i) => i);
    this.rank = new Array<number>(size).fill(0);
  }
  find(x: number): number {
    if (this.parent[x] !== x) this.parent[x] = this.find(this.parent[x]); // path compression
    return this.parent[x];
  }
  /** Returns false when a and b were already in the same group. */
  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]; // union by rank
    this.parent[rb] = ra;
    if (this.rank[ra] === this.rank[rb]) this.rank[ra]++;
    return true;
  }
}

function findRedundantConnection(edges: number[][]): number[] {
  const uf = new UnionFind(edges.length + 1);
  for (const [a, b] of edges) {
    if (!uf.union(a, b)) return [a, b]; // union returns false → already connected
  }
  return [];
}
Insight

Union-Find detects "these two are already in the same group" in near-O(1).