Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to find the root parent of a node in Union Find.
DSA Go
func find(parent []int, x int) int {
if parent[x] != x {
return [1]
}
return x
}Attempts:
3 left
💡 Hint
Common Mistakes
Returning parent[x] directly without recursion.
Returning x without checking if parent[x] == x.
✗ Incorrect
The find function recursively finds the root parent of x by calling find on parent[x].
2fill in blank
mediumComplete the code to perform path compression during find operation.
DSA Go
func find(parent []int, x int) int {
if parent[x] != x {
parent[x] = [1]
}
return parent[x]
}Attempts:
3 left
💡 Hint
Common Mistakes
Assigning parent[x] to x directly.
Calling find with x instead of parent[x].
✗ Incorrect
Path compression sets parent[x] to the root parent found by recursively calling find on parent[x].
3fill in blank
hardFix the error in the union function to correctly merge two sets.
DSA Go
func union(parent []int, x int, y int) {
rootX := find(parent, x)
rootY := find(parent, y)
if rootX != rootY {
[1] = rootX
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Assigning parent[x] or parent[y] instead of parent[rootY].
Assigning rootY directly without using parent array.
✗ Incorrect
To merge sets, set parent of rootY to rootX, linking rootY's tree under rootX.
4fill in blank
hardFill both blanks to implement union by rank optimization.
DSA Go
func union(parent []int, rank []int, x int, y int) {
rootX := find(parent, x)
rootY := find(parent, y)
if rootX != rootY {
if rank[rootX] < rank[rootY] {
[1] = rootY
} else if rank[rootX] > rank[rootY] {
[2] = rootX
} else {
parent[rootY] = rootX
rank[rootX]++
}
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Swapping rootX and rootY in assignments.
Assigning parent[x] or parent[y] instead of parent[rootX] or parent[rootY].
✗ Incorrect
If rank[rootX] < rank[rootY], set parent[rootX] = rootY; if rank[rootX] > rank[rootY], set parent[rootY] = rootX.
5fill in blank
hardFill all three blanks to implement find with path compression and union by rank.
DSA Go
func find(parent []int, x int) int {
if parent[x] != x {
parent[x] = [1]
}
return parent[x]
}
func union(parent []int, rank []int, x int, y int) {
rootX := find(parent, x)
rootY := find(parent, y)
if rootX != rootY {
if rank[rootX] < rank[rootY] {
[2] = rootY
} else if rank[rootX] > rank[rootY] {
[3] = rootX
} else {
parent[rootY] = rootX
rank[rootX]++
}
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Not using recursion in find for path compression.
Swapping parent assignments in union.
✗ Incorrect
In find, assign parent[x] = find(parent, parent[x]) for path compression. In union, assign parent[rootX] = rootY if rank[rootX] < rank[rootY], else parent[rootY] = rootX.
