Merge k Sorted Lists
The problem
Section titled “The problem”You get an array of k linked lists, each sorted ascending. Some may be empty. Merge them
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->6Key insight
Section titled “Key insight”Merging two sorted lists is easy: compare the two heads and take the smaller. With k lists, the naive version scans all k heads for every output node, which is O(N · k) where N is the total number of nodes.
The next output node is always the smallest of the current k heads. A min-heap of the
current heads finds it in O(log k). Pop the smallest, attach it to the result, and push
its next node if there is one. The heap never holds more than one node per list.
Show solutionHide solution
import heapq
def merge_k_lists(lists: list[ListNode | None]) -> ListNode | None: # (value, list index, node): the index breaks ties so nodes are never compared heap = [(head.val, i, head) for i, head in enumerate(lists) if head] heapq.heapify(heap) dummy = tail = ListNode() while heap: _, i, node = heapq.heappop(heap) tail.next = node tail = node if node.next: heapq.heappush(heap, (node.next.val, i, node.next)) return dummy.nextexport function mergeKLists(lists: (ListNode | null)[]): ListNode | null { // Heap: a standard binary heap (LeetCode provides MinPriorityQueue) const heap = new Heap<ListNode>((a, b) => a.val - b.val); // current head of each list for (const head of lists) if (head) heap.push(head); const dummy = new ListNode(); let tail = dummy; while (heap.size > 0) { const node = heap.pop()!; // smallest value among all heads tail.next = node; tail = node; if (node.next) heap.push(node.next); } return dummy.next;}import java.util.PriorityQueue;
class Solution { public ListNode mergeKLists(ListNode[] lists) { PriorityQueue<ListNode> heap = new PriorityQueue<>((a, b) -> Integer.compare(a.val, b.val)); // current head of each list for (ListNode head : lists) { if (head != null) heap.offer(head); } ListNode dummy = new ListNode(); ListNode tail = dummy; while (!heap.isEmpty()) { ListNode node = heap.poll(); // smallest value among all heads tail.next = node; tail = node; if (node.next != null) heap.offer(node.next); } return dummy.next; }}Complexity
Section titled “Complexity”- Time: O(N log k) — N nodes in total, and each is pushed and popped once on a heap of at most k nodes.
- Space: O(k) — the heap holds one node per list. The output reuses the existing nodes.
Watch out for
Section titled “Watch out for”- Skip empty lists. Some entries are
None/null, andlistsitself can be empty. Only push real heads; the result is then an empty list. - Python can’t compare
ListNodes. When two values tie, a bare(val, node)tuple falls through to comparing nodes and crashes. Put a unique index in between:(val, i, node). - Use a dummy head so you don’t special-case the first node.
- JS/TS interviews. There is no built-in heap. Say you will assume a heap helper
exists (LeetCode gives you
MinPriorityQueue) and offer to implement it.
Variations
Section titled “Variations”Kth Smallest Element in a Sorted Matrix (LeetCode 378)
Section titled “Kth Smallest Element in a Sorted Matrix (LeetCode 378)”Each row and column is sorted; find the kth smallest. The trick: treat each row as a sorted list. Seed a min-heap with the first item of each row and pop k times, pushing the next item in the popped item’s row.
Find K Pairs with Smallest Sums (LeetCode 373)
Section titled “Find K Pairs with Smallest Sums (LeetCode 373)”Given two sorted arrays, return the k pairs with the smallest sums. The trick: each
nums1[i] starts a sorted “list” of sums with every nums2[j]. Heap-merge those lists
and stop after k pops.
Smallest Range Covering Elements from K Lists (LeetCode 632)
Section titled “Smallest Range Covering Elements from K Lists (LeetCode 632)”Find the smallest range containing at least one number from each of k sorted lists. The
trick: a min-heap with one item per list, while tracking the current maximum. The range
is [heap top, max]; pop the top, push that list’s next item, and repeat.