Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to create a new queue for BFS traversal.
DSA Go
queue := make(chan *Node, [1]) Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using zero capacity channel causes deadlock.
Using capacity 1 is too small for BFS queue.
✗ Incorrect
We create a buffered channel with capacity 10 to hold nodes during BFS.
2fill in blank
mediumComplete the code to update the horizontal distance map only if the distance is not already present.
DSA Go
if _, ok := hdMap[hd]; ![1] { hdMap[hd] = node.data }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using variable names other than 'ok' for map presence check.
Not negating the condition to insert only once.
✗ Incorrect
The idiomatic way in Go to check map presence is using 'ok'.
3fill in blank
hardFix the error in the BFS loop to correctly update horizontal distance and enqueue children.
DSA Go
for len(queue) > 0 { node := <-queue hd := [1][node] if _, ok := hdMap[hd]; !ok { hdMap[hd] = node.data } if node.left != nil { queue <- node.left [2][node.left] = hd - 1 } if node.right != nil { queue <- node.right hdDist[node.right] = hd + 1 } }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'hdMap' to store horizontal distances causes wrong data.
Not updating horizontal distances for children.
✗ Incorrect
We use 'hdDist' map to track horizontal distances of nodes, not 'hdMap' which stores data.
4fill in blank
hardFill both blanks to correctly initialize the horizontal distance map and enqueue the root node.
DSA Go
hdDist := make(map[*Node]int) hdDist[[1]] = 0 queue <- [2]
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using different variable names for root causes errors.
Not initializing horizontal distance for root.
✗ Incorrect
We set the root node's horizontal distance to 0 and enqueue the root node.
5fill in blank
hardFill all three blanks to print the top view nodes in order of horizontal distance.
DSA Go
keys := make([]int, 0, len(hdMap)) for k := range hdMap { keys = append(keys, k) } sort.[1](sort.IntSlice(keys)) for _, k := range keys { fmt.[2](hdMap[k], " ") } fmt.[3]()
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong sort function causes compile error.
Using fmt.Println inside loop prints each node on new line.
✗ Incorrect
We use sort.Sort with sort.IntSlice, print with fmt.Print, and end line with fmt.Println.