Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to initialize the parent array so each element is its own parent.
DSA Java
for (int i = 0; i < n; i++) { parent[i] = [1]; }
Attempts:
3 left
💡 Hint
Common Mistakes
Setting all parents to 0 instead of their own index.
Using n as parent which is out of bounds.
✗ Incorrect
Each element starts as its own parent, so parent[i] = i.
2fill in blank
mediumComplete the code to find the root parent of element x with path compression.
DSA Java
int find(int x) {
if (parent[x] != x) {
parent[x] = [1];
}
return parent[x];
}Attempts:
3 left
💡 Hint
Common Mistakes
Assigning parent[x] to parent[parent[x]] which may not be root.
Returning x without updating parent[x].
✗ Incorrect
Path compression sets parent[x] to the root parent found recursively.
3fill in blank
hardFix the error in the union method to correctly merge two sets by rank.
DSA Java
void union(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]++;
}
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Swapping parents incorrectly causing cycles.
Not updating rank when ranks are equal.
✗ Incorrect
When rank[a] < rank[b], a's parent is b; when rank[a] > rank[b], b's parent is a.
4fill in blank
hardFill both blanks to check if two elements are in the same set.
DSA Java
boolean connected(int x, int y) {
return find(x) [1] find(y);
}Attempts:
3 left
💡 Hint
Common Mistakes
Using != which checks if they are in different sets.
Using < or > which are not meaningful here.
✗ Incorrect
Two elements are connected if their root parents are equal.
5fill in blank
hardFill all three blanks to implement union by size instead of rank.
DSA Java
void unionBySize(int a, int b) {
a = find(a);
b = find(b);
if (a != b) {
if (size[a] < size[b]) {
parent[a] = [1];
size[[2]] += size[a];
} else {
parent[b] = [3];
size[[3]] += size[b];
}
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Updating size of wrong root after union.
Swapping parent assignments incorrectly.
✗ Incorrect
Attach smaller size tree under bigger; update size of new parent accordingly.
