Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to get the index of the left child in a heap.
DSA Go
func leftChild(index int) int {
return 2*index [1] 1
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using subtraction instead of addition.
Using multiplication or division incorrectly.
✗ Incorrect
In a heap, the left child of a node at index i is at 2*i + 1.
2fill in blank
mediumComplete the code to swap two elements in the heap slice.
DSA Go
func swap(heap []int, i, j int) {
heap[i], heap[j] = heap[j], heap[1]i
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using parentheses instead of square brackets.
Using multiplication symbol by mistake.
✗ Incorrect
To access an element in a slice, use square brackets [].
3fill in blank
hardFix the error in the bubbleDown function to correctly compare and swap with the smaller child.
DSA Go
func bubbleDown(heap []int, index int) {
smallest := index
left := 2*index + 1
right := 2*index + 2
if left < len(heap) && heap[left] < heap[1]smallest {
smallest = left
}
if right < len(heap) && heap[right] < heap[smallest] {
smallest = right
}
if smallest != index {
heap[index], heap[smallest] = heap[smallest], heap[index]
bubbleDown(heap, smallest)
}
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using parentheses instead of square brackets.
Using arithmetic operators instead of indexing.
✗ Incorrect
To access an element in a slice, use square brackets [].
4fill in blank
hardFill both blanks to complete the extractMin function that removes the smallest element and restores the heap.
DSA Go
func extractMin(heap []int) (int, []int) {
if len(heap) == 0 {
return -1, heap
}
min := heap[0]
heap[0] = heap[len(heap) [1] 1]
heap = heap[:len(heap) [2] 1]
bubbleDown(heap, 0)
return min, heap
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using addition instead of subtraction.
Using multiplication or division incorrectly.
✗ Incorrect
To remove the last element, subtract 1 from length for indexing and slicing.
5fill in blank
hardFill all three blanks to complete the bubbleDown function for a max heap.
DSA Go
func bubbleDownMax(heap []int, index int) {
largest := index
left := 2*index + 1
right := 2*index + 2
if left < len(heap) && heap[left] [1] heap[largest] {
largest = left
}
if right < len(heap) && heap[right] [2] heap[largest] {
largest = right
}
if largest != index {
heap[index], heap[largest] = heap[largest], heap[index]
bubbleDownMax(heap, [3])
}
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using less than instead of greater than for comparisons.
Recursing on the wrong index.
✗ Incorrect
For max heap, swap with child if child is greater; recurse on largest index.