
Leetcode Problem 23: Merge k Sorted Lists
You receive k linked lists, and each individual list is already sorted in ascending order. Your task is to merge them into a single linked list that preserves the same global ordering.
list 0: 1 -> 4 -> 5
list 1: 1 -> 3 -> 4
list 2: 2 -> 6
merged: 1 -> 1 -> 2 -> 3 -> 4 -> 4 -> 5 -> 6
The challenge is to repeatedly choose the smallest current node among all lists until every node has been appended to the final result.
Constraints:
lists.length lists, so there may be anywhere from 0 to 10^4 lists.500 nodes.-10^4 to 10^4.10^4, which bounds the total merge work.import { Heap } from "../heap";
import { ListNode } from "../list-node";
function mergeKLists(lists: Array<ListNode | null>): ListNode | null {
const heap = new Heap<ListNode>((a, b) => a.val - b.val);
for (const node of lists) {
if (node !== null) {
heap.insert(node);
}
}
const dummy = new ListNode(0);
let curr = dummy;
while (heap.size() > 0) {
const minNode = heap.extract()!;
curr.next = minNode;
curr = curr.next;
if (minNode.next !== null) {
heap.insert(minNode.next);
}
}
return dummy.next;
}