Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to find the root parent of a node in Union Find.
DSA C#
int Find(int[] parent, int x) {
if (parent[x] == x) {
return x;
}
return [1];
}Attempts:
3 left
💡 Hint
Common Mistakes
Returning x directly without recursion.
Returning parent[x] without further recursion.
✗ Incorrect
The Find function recursively finds the root parent by calling Find on parent[x].
2fill in blank
mediumComplete the code to perform path compression in the Find function.
DSA C#
int Find(int[] parent, int x) {
if (parent[x] != x) {
parent[x] = [1];
}
return parent[x];
}Attempts:
3 left
💡 Hint
Common Mistakes
Assigning parent[x] to x directly.
Assigning parent[x] to parent[x] without recursion.
✗ Incorrect
Path compression sets parent[x] to the root by recursively calling Find on parent[x].
3fill in blank
hardFix the error in the Union function to correctly union two sets.
DSA C#
void Union(int[] parent, int a, int b) {
int rootA = Find(parent, a);
int rootB = Find(parent, b);
if (rootA != rootB) {
parent[[1]] = rootB;
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Using a or b instead of their roots.
Setting parent of rootB instead of rootA.
✗ Incorrect
We set parent of rootA to rootB to union the two sets.
4fill in blank
hardFill both blanks to implement path compression and return the root.
DSA C#
int Find(int[] parent, int x) {
if (parent[x] != x) {
parent[x] = [1];
}
return [2];
}Attempts:
3 left
💡 Hint
Common Mistakes
Returning x instead of parent[x].
Not updating parent[x] recursively.
✗ Incorrect
First, update parent[x] to the root by calling Find on parent[x]. Then return parent[x].
5fill in blank
hardFill all three blanks to implement Union Find with path compression correctly.
DSA C#
int Find(int[] parent, int x) {
if (parent[x] != x) {
parent[x] = [1];
}
return parent[x];
}
void Union(int[] parent, int a, int b) {
int rootA = Find(parent, a);
int rootB = Find(parent, b);
if (rootA != rootB) {
parent[[2]] = [3];
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Not compressing path in Find.
Using wrong variables in Union assignment.
✗ Incorrect
In Find, update parent[x] to root by calling Find on parent[x]. In Union, set parent of rootA to rootB.
