class UnionFind {
parent: number[];
constructor(size: number) {
this.parent = Array(size + 1).fill(0).map((_, i) => i);
}
find(x: number): number {
if (this.parent[x] !== x) {
this.parent[x] = this.find(this.parent[x]); // path compression
}
return this.parent[x];
}
union(a: number, b: number): void {
const rootA = this.find(a);
const rootB = this.find(b);
if (rootA !== rootB) {
this.parent[rootA] = rootB; // link rootA to rootB
}
}
}
// Driver code
const uf = new UnionFind(4);
uf.union(1, 2);
uf.union(2, 3);
uf.union(3, 4);
console.log('Parent array after unions:', uf.parent.slice(1).join(' '));
const leader = uf.find(1);
console.log('Leader of 1 is', leader);
console.log('Parent array after path compression:', uf.parent.slice(1).join(' '));if (this.parent[x] !== x) {
check if current node is not leader
this.parent[x] = this.find(this.parent[x]); // path compression
recursively find leader and update current node to point directly to leader
return leader of current node
const rootA = this.find(a);
find leader of element a
const rootB = this.find(b);
find leader of element b
only union if leaders differ
this.parent[rootA] = rootB; // link rootA to rootB
attach rootA's tree under rootB to merge sets
Parent array after unions: 2 3 4 4
Leader of 1 is 4
Parent array after path compression: 4 4 4 4