Complete the code to find the root parent of a node in Union Find.
int find(int x) {
if (parent[x] == x) {
return x;
}
return [1];
}The find function recursively finds the root parent of x by calling find on its parent until it reaches the root.
Complete the code to apply path compression in the find function.
int find(int x) {
if (parent[x] != x) {
parent[x] = [1];
}
return parent[x];
}Path compression sets the parent of x directly to the root parent found by recursively calling find on parent[x].
Fix the error in the union function to correctly merge two sets.
void unionSets(int a, int b) {
a = find(a);
b = find(b);
if (a != b) {
parent[a] = [1];
}
}To merge two sets, we set the parent of root a to root b, effectively connecting the two sets.
Fill both blanks to implement union by rank optimization.
void unionSets(int a, int b) {
a = find(a);
b = find(b);
if (a != b) {
if (rank[a] < rank[b]) {
parent[a] = [1];
} else if (rank[a] > rank[b]) {
parent[b] = [2];
} else {
parent[b] = a;
rank[a]++;
}
}
}If rank[a] is less, attach a to b. If rank[b] is less, attach b to a. This keeps trees shallow.
Fill all three blanks to implement path compression and union by rank in union-find.
int find(int x) {
if (parent[x] != x) {
parent[x] = [1];
}
return parent[x];
}
void unionSets(int a, int b) {
a = find(a);
b = find(b);
if (a != b) {
if (rank[a] < rank[b]) {
parent[a] = [2];
} else if (rank[a] > rank[b]) {
parent[b] = [3];
} else {
parent[b] = a;
rank[a]++;
}
}
}The find function uses path compression by setting parent[x] to the root found by find(parent[x]). The union function attaches the smaller rank tree under the bigger rank tree.
