3. What will be the output of the following code snippet that merges 3 sorted lists using a min heap?
const lists = [[1,4,5],[1,3,4],[2,6]];
function mergeKLists(lists) {
const minHeap = [];
const result = [];
for (let i = 0; i < lists.length; i++) {
if (lists[i].length > 0) minHeap.push({ val: lists[i][0], listIndex: i, elementIndex: 0 });
}
minHeap.sort((a,b) => a.val - b.val);
while (minHeap.length > 0) {
const smallest = minHeap.shift();
result.push(smallest.val);
const nextIndex = smallest.elementIndex + 1;
if (nextIndex < lists[smallest.listIndex].length) {
minHeap.push({ val: lists[smallest.listIndex][nextIndex], listIndex: smallest.listIndex, elementIndex: nextIndex });
minHeap.sort((a,b) => a.val - b.val);
}
}
return result;
}
console.log(mergeKLists(lists));