Complete the code to initialize the min heap as an empty array.
const minHeap = [1];We use an empty array [] to represent the min heap initially.
Complete the code to push the first node of each list into the min heap.
for (let i = 0; i < lists.length; i++) { if (lists[i]) { minHeap.push({ val: lists[i].val, listIndex: i, node: lists[i] }); } } // Now build the heap for (let i = Math.floor(minHeap.length / 2) - 1; i >= 0; i--) { [1](minHeap, i); }
We call heapify to build the min heap from the array.
Fix the error in the function that extracts the minimum element from the heap.
function extractMin(heap) {
if (heap.length === 0) return null;
const min = heap[0];
heap[0] = heap[heap.length - 1];
heap.pop();
[1](heap, 0);
return min;
}After removing the root, we call heapify to restore the min heap property.
Fill both blanks to insert the next node from the extracted list into the heap and maintain the heap property.
if (min.node.next) { minHeap.push({ val: min.node.next.val, listIndex: min.listIndex, node: min.node.next }); [1](minHeap, minHeap.length - 1); } function [2](heap, index) { // heapifyDown implementation }
We call heapifyUp after pushing a new element to fix upwards, and heapifyDown is the function that fixes downwards.
Fill all three blanks to complete the main loop that extracts the smallest node and appends it to the merged list.
while (minHeap.length > 0) { const min = [1](minHeap); current.next = min.node; current = current.next; if (min.node.next) { minHeap.push({ val: min.node.next.val, listIndex: min.listIndex, node: min.node.next }); [2](minHeap, minHeap.length - 1); } [3](minHeap, 0); }
We extract the minimum node with extractMin, fix the heap upwards after pushing a new node with heapifyUp, and fix downwards with heapifyDown.