Complete the code to find the root parent of a node with path compression.
int find(int x) {
if (parent[x] != x) {
parent[x] = [1];
}
return parent[x];
}The find function recursively finds the root parent of x and applies path compression by setting parent[x] to the root.
Complete the union function to merge two sets by their root parents.
void union(int a, int b) {
int rootA = find(a);
int rootB = find(b);
if (rootA != rootB) {
parent[[1]] = rootB;
}
}We set the parent of rootA to rootB to merge the two sets.
Fix the error in the find function to correctly apply path compression.
int find(int x) {
if (parent[x] == x) {
return x;
}
return [1];
}The function must recursively call find on parent[x] to find the root and apply path compression.
Fill both blanks to implement path compression in the find function.
int find(int x) {
if (parent[x] != x) {
parent[x] = [1];
}
return [2];
}We assign parent[x] to the root found by find(parent[x]) and then return parent[x].
Fill all three blanks to implement union by rank with path compression.
void union(int a, int b) {
int rootA = find(a);
int rootB = find(b);
if (rootA != rootB) {
if (rank[rootA] < rank[[1]]) {
parent[rootA] = [2];
} else if (rank[rootA] > rank[rootB]) {
parent[[3]] = rootA;
} else {
parent[rootB] = rootA;
rank[rootA]++;
}
}
}We compare ranks of rootA and rootB. If rank[rootA] < rank[rootB], parent[rootA] = rootB. If rank[rootA] > rank[rootB], parent[rootB] = rootA. Otherwise, parent[rootB] = rootA and increment rank[rootA].
