Complete the code to find the root parent of a node with path compression.
function find(parent, x) {
if (parent[x] !== x) {
parent[x] = [1];
}
return parent[x];
}The function recursively finds the root parent and updates the parent of x to that root, which is path compression.
Complete the union function to merge two sets by their root parents.
function union(parent, x, y) {
let rootX = find(parent, x);
let rootY = find(parent, y);
if (rootX !== rootY) {
[1] = rootY;
}
}We set the parent of rootX to rootY to merge the two sets.
Fix the error in the find function to correctly implement path compression.
function find(parent, x) {
if (parent[x] === x) {
return x;
}
parent[x] = [1];
return parent[x];
}We must recursively call find on parent[x] to get the root and assign it to parent[x] for path compression.
Fill both blanks to complete the union function with path compression.
function union(parent, x, y) {
let rootX = [1];
let rootY = [2];
if (rootX !== rootY) {
parent[rootX] = rootY;
}
}We find the root parents of x and y before union to ensure correct merging.
Fill all three blanks to implement a union-find with path compression and union by rank.
function union(parent, rank, x, y) {
let rootX = [1];
let rootY = [2];
if (rootX !== rootY) {
if (rank[rootX] < rank[rootY]) {
parent[rootX] = rootY;
} else if (rank[rootX] > rank[rootY]) {
parent[rootY] = rootX;
} else {
parent[rootY] = rootX;
rank[rootX][3]1;
}
}
}We find root parents first, then update parent and rank correctly to keep tree balanced.
