Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to initialize the parent array for union-find.
DSA Go
parent := make([]int, n) for i := 0; i < n; i++ { parent[i] = [1] }
Attempts:
3 left
💡 Hint
Common Mistakes
Setting all parents to 0 causes incorrect union-find behavior.
Using -1 or n as parent values breaks the logic.
✗ 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 Go
func find(parent []int, x int) int {
if parent[x] != x {
parent[x] = [1](parent, parent[x])
}
return parent[x]
}Attempts:
3 left
💡 Hint
Common Mistakes
Calling union instead of find causes errors.
Using parent directly without recursion breaks path compression.
✗ Incorrect
The find function calls itself recursively to find the root parent and compress the path.
3fill in blank
hardFix the error in the union function to correctly merge two sets.
DSA Go
func union(parent []int, a, b int) {
rootA := find(parent, a)
rootB := find(parent, b)
if rootA != rootB {
parent[rootB] = [1]
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Assigning parent[rootB] = b or a causes incorrect unions.
Assigning parent[rootB] = rootB does nothing.
✗ Incorrect
To merge sets, set the parent of rootB to rootA.
4fill in blank
hardFill both blanks to check if adding an edge creates a cycle and to union sets if not.
DSA Go
for _, edge := range edges { if find(parent, edge.u) [1] find(parent, edge.v) { union(parent, edge.u, edge.v) mstWeight += edge.weight } }
Attempts:
3 left
💡 Hint
Common Mistakes
Using '==' causes cycles by adding edges within the same set.
Using '<' or '>' is not meaningful for root comparison.
✗ Incorrect
We add the edge only if the roots of u and v are different to avoid cycles.
5fill in blank
hardFill all three blanks to sort edges by weight, initialize MST weight, and iterate edges.
DSA Go
sort.Slice(edges, func(i, j int) bool {
return edges[i].[1] < edges[j].[2]
})
mstWeight := [3]
for _, edge := range edges {
if find(parent, edge.u) != find(parent, edge.v) {
union(parent, edge.u, edge.v)
mstWeight += edge.weight
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Sorting by u or other fields breaks MST correctness.
Not initializing mstWeight causes wrong total weight.
✗ Incorrect
Sort edges by their weight field, initialize mstWeight to 0 before adding edges.
