Complete the code to find the root parent of a node in Union Find.
function find(parent: number[], x: number): number {
if (parent[x] === x) {
return x;
}
return find(parent, [1]);
}The find function recursively finds the root parent of x by following parent pointers. The correct recursive call is find(parent, parent[x]) to move up the tree.
Complete the code to perform path compression in the find function.
function find(parent: number[], x: number): number {
if (parent[x] !== x) {
parent[x] = [1];
}
return parent[x];
}Path compression sets parent[x] to the root parent found by recursively calling find on parent[x]. This flattens the tree for faster future queries.
Fix the error in the union function to correctly merge two sets.
function union(parent: number[], x: number, y: number): void {
const rootX = find(parent, x);
const rootY = find(parent, y);
if (rootX !== rootY) {
parent[[1]] = rootY;
}
}To merge two sets, we set the parent of rootX to rootY. Using rootX ensures the root of x's set points to rootY.
Fill both blanks to implement union by rank optimization.
function union(parent: number[], rank: number[], x: number, y: number): void {
const rootX = find(parent, x);
const rootY = find(parent, y);
if (rootX !== rootY) {
if (rank[rootX] [1] rank[rootY]) {
parent[rootY] = rootX;
} else if (rank[rootX] [2] rank[rootY]) {
parent[rootX] = rootY;
} else {
parent[rootY] = rootX;
rank[rootX]++;
}
}
}Union by rank attaches the smaller tree under the larger tree. If rank[rootX] > rank[rootY], rootY points to rootX. If rank[rootX] < rank[rootY], rootX points to rootY.
Fill all three blanks to implement the find function with path compression and union by rank.
function find(parent: number[], rank: number[], x: number): number {
if (parent[x] !== x) {
parent[x] = [1];
}
return parent[x];
}
function union(parent: number[], rank: number[], x: number, y: number): void {
const rootX = find(parent, rank, x);
const rootY = find(parent, rank, y);
if (rootX !== rootY) {
if (rank[rootX] [2] rank[rootY]) {
parent[rootY] = rootX;
} else if (rank[rootX] [3] rank[rootY]) {
parent[rootX] = rootY;
} else {
parent[rootY] = rootX;
rank[rootX]++;
}
}
}The find function uses path compression by recursively calling find with parent[x] and assigning the result to parent[x]. The union function compares ranks with > and < to decide which root becomes parent.