Skip to content

Merge k Sorted Lists

HardLeetCode #23Time O(N log k)Space O(k)

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->6

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.next
  • 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.
  • Skip empty lists. Some entries are None/null, and lists itself 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.

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.