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 Go
for i := 0; i < n; i++ { parent[i] = [1] }
Attempts:
3 left
💡 Hint
Common Mistakes
Setting all parents to 0 causes wrong unions.
Using -1 or n as parent leads to invalid references.
✗ 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 Go
func find(x int) int {
if parent[x] != x {
parent[x] = [1](parent[x])
}
return parent[x]
}Attempts:
3 left
💡 Hint
Common Mistakes
Using union instead of find causes errors.
Assigning parent[x] to parent[x] does nothing.
✗ Incorrect
We recursively call find to get the root and compress the path.
3fill in blank
hardFix the error in the union function to correctly merge two sets.
DSA Go
func union(x, y int) {
rootX := find(x)
rootY := find(y)
if rootX != rootY {
parent[[1]] = rootY
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Updating parent[x] or parent[y] instead of root parents.
Assigning parent[rootY] = rootX reverses the union.
✗ Incorrect
We set the parent of rootX to rootY to merge the sets.
4fill in blank
hardFill both blanks to check if two elements are in the same set.
DSA Go
func connected(x, y int) bool {
return find([1]) == find([2])
}Attempts:
3 left
💡 Hint
Common Mistakes
Using rootX or rootY which are undefined here.
Comparing x and y directly without find.
✗ Incorrect
We check if the roots of x and y are the same to confirm connection.
5fill in blank
hardFill all three blanks to implement union by rank optimization.
DSA Go
func union(x, y int) {
rootX := find(x)
rootY := find(y)
if rootX != rootY {
if rank[[1]] < rank[[2]] {
parent[rootX] = rootY
} else if rank[rootX] > rank[rootY] {
parent[rootY] = rootX
} else {
parent[rootY] = rootX
rank[[3]]++
}
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Using original elements x or y instead of root parents.
Increasing rank of wrong element.
✗ Incorrect
We compare ranks of rootX and rootY, update parents accordingly, and increase rank of rootX if equal.
