Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to initialize the parent array for union-find.
DSA Javascript
const parent = Array(n).fill().map((_, i) => [1]);Attempts:
3 left
💡 Hint
Common Mistakes
Setting all parents to 0 or -1 causes incorrect union-find behavior.
✗ Incorrect
Each node is initially its own parent, so parent[i] = i.
2fill in blank
mediumComplete the code to find the root parent of a node with path compression.
DSA Javascript
function find(x) {
if (parent[x] !== x) {
parent[x] = [1](parent[x]);
}
return parent[x];
}Attempts:
3 left
💡 Hint
Common Mistakes
Using union or other functions instead of find causes errors.
✗ Incorrect
The find function calls itself recursively to find the root parent.
3fill in blank
hardFix the error in the union function to correctly merge two sets.
DSA Javascript
function union(a, b) {
a = find(a);
b = find(b);
if (a !== b) {
parent[[1]] = [2];
return true;
}
return false;
}Attempts:
3 left
💡 Hint
Common Mistakes
Assigning parent[a] to parent[b] instead of parent[a] to b.
Mixing up a and b in assignment.
✗ Incorrect
We set parent of root a to root b to merge sets.
4fill in blank
hardFill both blanks to sort edges by weight and iterate over them.
DSA Javascript
edges.[1]((a, b) => a.[2] - b.[2]); for (const edge of edges) { // process edge }
Attempts:
3 left
💡 Hint
Common Mistakes
Using reverse instead of sort.
Comparing by length or other properties.
✗ Incorrect
We sort edges by their weight property using sort and weight.
5fill in blank
hardFill all three blanks to build the MST using union-find and accumulate total weight.
DSA Javascript
let mstWeight = 0; for (const [1] of edges) { if (union([2], [3])) { mstWeight += edge.weight; } }
Attempts:
3 left
💡 Hint
Common Mistakes
Using edges instead of edge in the loop.
Mixing up edge.u and edge.v.
✗ Incorrect
We iterate over each edge, union its nodes u and v, and add weight if union succeeds.
