Union Find With Path Compression Typed

Implement a typed disjoint set union find with path compression and union by rank for near constant amortized time.

TypescriptData Integrity

Code

typescriptsnippet
7 lines
class UnionFind {
  private parent: number[]; private rank: number[]; count: number;
  constructor(n: number) { this.parent = Array.from({ length: n }, (_, i) => i); this.rank = new Array(n).fill(0); this.count = n; }
  find(x: number): number { while (this.parent[x] !== x) { this.parent[x] = this.parent[this.parent[x]]; x = this.parent[x]; } return x; }
  union(a: number, b: number): boolean { const ra = this.find(a), rb = this.find(b); if (ra === rb) return false; if (this.rank[ra] < this.rank[rb]) this.parent[ra] = rb; else if (this.rank[ra] > this.rank[rb]) this.parent[rb] = ra; else { this.parent[rb] = ra; this.rank[ra]++; } this.count--; return true; }
  connected(a: number, b: number): boolean { return this.find(a) === this.find(b); }
}

How the snippet works

Count the class UnionFind as the entire surface area of Union Find With Path Compression Typed.

Caveats

  • The guard ra === rb short-circuits the flow with an early return when its condition holds.

Statements that matter

constructor(n: number) { this.parent = Array.from({ length: n }, (_, i) => i); this.rank = new Array(n).fill(0); this.count = n; }
connected(a: number, b: number): boolean { return this.find(a) === this.find(b); }

Interactive Tools for This Topic

FAQ

Does it depend on any third-party library?
No third-party library is referenced; the standard library covers it.