The problem. You're given an array of k linked lists, each sorted in ascending order. Merge them all into one sorted linked list and return its head.
lists = [[1,4,5], [1,3,4], [2,6]] -> [1,1,2,3,4,4,5,6]
lists = [] -> []
lists = [[]] -> []Below, N is the total number of nodes in all the lists, and k is the number of lists.
function mergeKLists(lists) { const values = []; for (let node of lists) for (; node; node = node.next) values.push(node.val); // collect every value values.sort((a, b) => a - b); const dummy = new ListNode(0); let tail = dummy; for (const v of values) tail = tail.next = new ListNode(v); // rebuild one sorted list return dummy.next;}Time O(N log N), space O(N). It throws away the fact that every list is already sorted, and builds N new nodes.
Merging two sorted lists is easy — walk both, always taking the smaller head (the Merge Two Sorted Lists problem from the Linked List course). So fold the lists in one by one: merge list 0 with list 1, the result with list 2, and so on.
function mergeKLists(lists) { let merged = null; for (const list of lists) merged = mergeTwo(merged, list); // fold the lists in one by one return merged;} function mergeTwo(a, b) { const dummy = new ListNode(0); let tail = dummy; while (a && b) { if (a.val <= b.val) { tail.next = a; a = a.next; } // take the smaller head else { tail.next = b; b = b.next; } tail = tail.next; } tail.next = a ?? b; // one list may have nodes left return dummy.next;}Time O(k · N), space O(1). No new nodes — but the merged list keeps growing, and every fold walks it again: the first list's nodes are walked k − 1 times.
The smallest node of all is always one of the k heads. Put the heads in a min-heap: pop the smallest, link it onto the result, and push its next node — the new head of that list. The heap never holds more than k nodes, so each step costs O(log k).
The heap holds one head per list; every pop moves that list forward by one node.
function mergeKLists(lists) { const heap = new Heap((a, b) => a.val - b.val); // the current head of each list for (const head of lists) if (head) heap.push(head); const dummy = new ListNode(0); let tail = dummy; while (heap.size() > 0) { const node = heap.pop(); // the smallest head of all tail.next = node; tail = node; if (node.next) heap.push(node.next); // its list moves forward } return dummy.next;}Time O(N log k), space O(k) for the heap. Python puts the list number in each tuple: without it, two equal values would make Python compare two ListNodes, which raises a TypeError.
O(N log N)Sorts all N values, ignoring that each list is sorted.
O(N)The values and N new nodes.
[]: return null.[[], []]: skip null heads when filling the heap.[value, array, index].O(k · N)The merged list grows, and each of the k folds walks it again.
O(1)Nodes are relinked, never copied.
O(N log k)Each of the N nodes is pushed and popped once on a heap of k heads.
O(k)The heap holds one head per list.