Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to initialize the parent array where each element is its own parent.
DSA Rust
let mut parent = vec![0; n]; for i in 0..n { parent[i] = [1]; }
Attempts:
3 left
💡 Hint
Common Mistakes
Setting all parents to 0 or -1 instead of their own index.
Using n as the parent value for all elements.
✗ Incorrect
Each element is initially its own parent, so we set parent[i] = i for all i.
2fill in blank
mediumComplete the code to find the root parent of element x with path compression.
DSA Rust
fn find(parent: &mut Vec<usize>, x: usize) -> usize {
if parent[x] != x {
parent[x] = [1](parent, parent[x]);
}
parent[x]
}Attempts:
3 left
💡 Hint
Common Mistakes
Using union instead of find inside the function.
Calling a non-existent function like root or get_parent.
✗ Incorrect
The find function calls itself recursively to find the root parent and compresses the path.
3fill in blank
hardFix the error in the union function to correctly merge two sets by their root parents.
DSA Rust
fn union(parent: &mut Vec<usize>, x: usize, y: usize) {
let root_x = find(parent, x);
let root_y = find(parent, y);
if root_x != root_y {
parent[[1]] = root_y;
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Using x or y directly instead of their roots.
Setting parent of root_y instead of root_x.
✗ Incorrect
We set the parent of root_x to root_y to merge the two sets.
4fill in blank
hardFill both blanks to check if two elements are in the same set.
DSA Rust
fn connected(parent: &mut Vec<usize>, x: usize, y: usize) -> bool {
find(parent, [1]) == find(parent, [2])
}Attempts:
3 left
💡 Hint
Common Mistakes
Using root_x or root_y which are not defined in this scope.
Comparing x and y directly without finding their roots.
✗ Incorrect
We check if the roots of x and y are the same to determine if they are connected.
5fill in blank
hardFill all three blanks to implement union by rank optimization.
DSA Rust
fn union_by_rank(parent: &mut Vec<usize>, rank: &mut Vec<usize>, x: usize, y: usize) {
let root_x = find(parent, x);
let root_y = find(parent, y);
if root_x != root_y {
if rank[root_x] [1] rank[root_y] {
parent[[2]] = root_x;
} else if rank[root_x] < rank[root_y] {
parent[[3]] = root_y;
} else {
parent[root_y] = root_x;
rank[root_x] += 1;
}
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Mixing up the comparison operators.
Assigning parents incorrectly causing cycles.
✗ Incorrect
We compare ranks to attach the smaller tree under the bigger one and update parents accordingly.
