Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to push the first element of each list into the min heap.
DSA Python
for i in range(len(lists)): if lists[i]: heapq.heappush([1], (lists[i][0], i, 0))
Attempts:
3 left
💡 Hint
Common Mistakes
Using the wrong variable name instead of the heap.
Pushing the entire list instead of the first element.
✗ Incorrect
We use 'min_heap' to store the first element of each list along with its list index and element index.
2fill in blank
mediumComplete the code to pop the smallest element from the min heap.
DSA Python
while min_heap: val, list_idx, element_idx = heapq.[1](min_heap)
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'push' instead of 'heappop'.
Using 'peek' which does not remove the element.
✗ Incorrect
We use 'heappop' to remove and return the smallest element from the min heap.
3fill in blank
hardFix the error in the code to push the next element of the same list into the min heap.
DSA Python
if element_idx + 1 < len(lists[list_idx]): heapq.heappush(min_heap, (lists[list_idx][[1]], list_idx, element_idx + 1))
Attempts:
3 left
💡 Hint
Common Mistakes
Using the current element index instead of the next.
Using the list index instead of element index.
✗ Incorrect
We push the next element at index 'element_idx + 1' from the same list into the heap.
4fill in blank
hardFill both blanks to append the smallest value to the result list and pop it from the heap.
DSA Python
val, list_idx, element_idx = heapq.[1](min_heap) result.[2](val)
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'pop' instead of 'heappop' for the heap.
Using 'push' instead of 'append' for the list.
✗ Incorrect
We pop the smallest element using 'heappop' and append its value to the result list.
5fill in blank
hardFill all three blanks to complete the merge function using a min heap.
DSA Python
import heapq def merge_k_lists(lists): min_heap = [] result = [] for i in range(len(lists)): if lists[i]: heapq.heappush(min_heap, (lists[i][0], i, 0)) while min_heap: val, list_idx, element_idx = heapq.[1](min_heap) result.[2](val) if element_idx + 1 < len(lists[list_idx]): heapq.heappush(min_heap, (lists[list_idx][[3]], list_idx, element_idx + 1)) return result
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'pop' instead of 'heappop' for the heap.
Appending the wrong variable to the result.
Using the wrong index for the next element.
✗ Incorrect
We pop the smallest element with 'heappop', append its value, and push the next element at 'element_idx + 1'.
