Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to swap two elements in the slice.
DSA Go
func swap(arr []int, i, j int) {
temp := arr[[1]]
arr[i] = arr[j]
arr[j] = temp
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using the wrong index like j or 0 for temp storage.
Forgetting to store the value before overwriting.
✗ Incorrect
The swap function uses the index i to temporarily store the value before swapping.
2fill in blank
mediumComplete the code to find the left child index in the heap.
DSA Go
func leftChild(i int) int {
return 2*[1] + 1
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using a fixed number instead of the variable i.
Adding 2 instead of 1.
✗ Incorrect
The left child index in a heap is calculated as 2*i + 1.
3fill in blank
hardFix the error in the heapify function to correctly compare parent and child nodes.
DSA Go
func heapify(arr []int, n, i int) {
largest := i
l := 2*i + 1
r := 2*i + 2
if l < n && arr[l] [1] arr[largest] {
largest = l
}
if r < n && arr[r] > arr[largest] {
largest = r
}
if largest != i {
swap(arr, i, largest)
heapify(arr, n, largest)
}
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using '<' which breaks max-heap property.
Using '==' or '!=' which are incorrect for comparison.
✗ Incorrect
To maintain max-heap property, we check if child is greater than parent.
4fill in blank
hardFill both blanks to build the max heap from the array.
DSA Go
func buildMaxHeap(arr []int, n int) {
for i := n/[1] - 1; i >= 0; i-- {
heapify(arr, n, [2])
}
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using n or 1 instead of 2 for division.
Passing wrong index to heapify.
✗ Incorrect
We start heapify from the last parent node at n/2 -1 down to 0.
5fill in blank
hardFill all three blanks to complete the heap sort main loop.
DSA Go
func heapSort(arr []int) {
n := len(arr)
buildMaxHeap(arr, n)
for i := n - 1; i > 0; i-- {
swap(arr, 0, [1])
heapify(arr, [2], [3])
}
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong indices for swap or heapify.
Not reducing heap size correctly.
✗ Incorrect
Swap root with last element i, then heapify with reduced size i and root index 0.