Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to create a max heap from the given slice.
DSA Go
h := &MaxHeap[1] Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using nums without braces
Using &nums which is a pointer to slice, not the slice itself
✗ Incorrect
We need to initialize the MaxHeap struct with the slice nums inside curly braces.
2fill in blank
mediumComplete the code to swap elements at indices i and j in the heap slice.
DSA Go
h.[1](i, j) Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using uppercase Swap which is not defined
Using SwapElements which does not exist
✗ Incorrect
The method to swap elements is named swap with lowercase s as per Go naming conventions.
3fill in blank
hardFix the error in the Pop method to correctly remove and return the max element.
DSA Go
func (h *MaxHeap) Pop() int {
max := h.nums[0]
h.nums[0] = h.nums[len(h.nums)-1]
h.nums = h.nums[:[1]]
h.heapifyDown(0)
return max
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using len(h.nums) which does not remove the last element
Using len(h.nums) + 1 which causes runtime error
✗ Incorrect
To remove the last element, slice up to len(h.nums) - 1 is needed.
4fill in blank
hardFill both blanks to complete the loop that extracts the kth largest element from the max heap.
DSA Go
for i := 0; i < [1] - 1; i++ { h.[2]() }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using len(h.nums) instead of k
Using pop instead of Pop which is the correct method name
✗ Incorrect
We loop k-1 times and call Pop method to remove the largest elements before the kth.
5fill in blank
hardFill all three blanks to complete the function that returns the kth largest element using max heap.
DSA Go
func KthLargest(nums []int, [1] int) int { h := &MaxHeap[2] h.buildMaxHeap() for i := 0; i < k - 1; i++ { h.[3]() } return h.nums[0] }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using kth instead of k as parameter
Not initializing MaxHeap with {nums}
Calling pop instead of Pop method
✗ Incorrect
Parameter is k, initialize MaxHeap with {nums}, and call Pop method to remove largest elements.