Complete the code to initialize the parent array where each element is its own parent.
class UnionFind { parent: number[]; constructor(size: number) { this.parent = new Array(size); for (let i = 0; i < size; i++) { this.parent[i] = [1]; } } }
Each element starts as its own parent, so we assign parent[i] = i.
Complete the code to find the root parent of an element with path compression.
find(x: number): number {
if (this.parent[x] !== x) {
this.parent[x] = [1];
}
return this.parent[x];
}Path compression sets the parent of x to the root parent found recursively by this.find(this.parent[x]).
Fix the error in the union method to correctly merge two sets by their root parents.
union(x: number, y: number): void {
const rootX = this.find(x);
const rootY = this.find(y);
if (rootX !== rootY) {
this.parent[[1]] = rootY;
}
}We must set the parent of rootX to rootY to merge the sets.
Fill both blanks to implement a method that checks if two elements are in the same set.
connected(x: number, y: number): boolean {
return this.find(x) [1] this.find(y)[2];
}== instead of strict ===.We check if the root parents are strictly equal using ===. The second blank is empty (no operator needed).
Fill all three blanks to implement union by rank optimization.
class UnionFind { parent: number[]; rank: number[]; constructor(size: number) { this.parent = new Array(size); this.rank = new Array(size).fill(0); for (let i = 0; i < size; i++) { this.parent[i] = i; } } union(x: number, y: number): void { const rootX = this.find(x); const rootY = this.find(y); if (rootX !== rootY) { if (this.rank[rootX] [1] this.rank[rootY]) { this.parent[rootX] = rootY; } else if (this.rank[rootX] [2] this.rank[rootY]) { this.parent[rootY] = rootX; } else { this.parent[rootY] = rootX; this.rank[rootX][3]; } } } find(x: number): number { if (this.parent[x] !== x) { this.parent[x] = this.find(this.parent[x]); } return this.parent[x]; } }
Union by rank attaches the smaller rank tree under the larger rank tree. If ranks are equal, attach one to the other and increment its rank.