Complete the code to initialize the parent array where each element is its own parent.
class UnionFind { constructor(size) { 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 i to parent[i].
Complete the code to find the root parent of an element with path compression.
find(x) {
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 find.
Fix the error in the union method to correctly merge two sets by their root parents.
union(a, b) {
let rootA = this.find(a);
let rootB = this.find(b);
if (rootA !== rootB) {
this.parent[[1]] = [2];
}
}We set the parent of rootA to rootB to merge the two sets.
Fill both blanks to check if two elements belong to the same set.
connected(a, b) {
return this.find(a) [1] this.find(b);
}Two elements are connected if their root parents are strictly equal.
Fill all three blanks to implement union by rank optimization.
class UnionFind { constructor(size) { this.parent = new Array(size); this.rank = new Array(size).fill(0); for (let i = 0; i < size; i++) { this.parent[i] = i; } } find(x) { if (this.parent[x] !== x) { this.parent[x] = this.find(this.parent[x]); } return this.parent[x]; } union(a, b) { let rootA = this.find(a); let rootB = this.find(b); if (rootA !== rootB) { if (this.rank[rootA] [1] this.rank[rootB]) { this.parent[rootA] = rootB; } else if (this.rank[rootA] [2] this.rank[rootB]) { this.parent[rootB] = rootA; } else { this.parent[rootB] = rootA; this.rank[rootA] [3] 1; } } } }
Union by rank attaches the smaller tree under the larger one. If ranks are equal, attach and increase rank.
