Merge k Sorted Lists LeetCode solution in JavaScript

1
var mergeKLists = function (lists) {
2
// Use min heap to keep track of the smallest node in constant time.
3
// Enqueue and dequeue will be log(k) where k is the # of lists
4
// b/c we only need to keep track of the next node for each list
5
// at any given time.
6
const minHeap = new MinPriorityQueue({ priority: (item) => item.val });
7

8
for (let head of lists) {
9
if (head) minHeap.enqueue(head);
10
}
11

12
// Create tempHead that we initiate the new list with
13
// Final list will start at tempHead.next
14
const tempHead = new ListNode();
15
let curr = tempHead;
16

17
while (!minHeap.isEmpty()) {
18
const { val, next } = minHeap.dequeue().element;
19
curr.next = new ListNode(val);
20
curr = curr.next;
21

22
if (next) minHeap.enqueue(next);
23
}
24

25
return tempHead.next;
26
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0