LeetCode #23 Hard

Merge K Sorted Lists

Merge K Sorted Lists is LeetCode 23 (Hard). You are given an array lists of k linked lists, each sorted in ascending order.

Merge them into one sorted linked list and return its head.

  • k can be 0, and any list can be empty.
  • There are at most 10⁴ nodes in total, but k can also be 10⁴, so scanning all k heads for every node can reach 10⁸ steps.
Constraints
  • k == lists.length
  • 0 <= k <= 10⁴
  • 0 <= lists[i].length <= 500
  • -10⁴ <= lists[i][j] <= 10⁴
  • lists[i] is sorted in ascending order
  • The total number of nodes is at most 10⁴
heaplinked-listdivide-and-conquer
Open on LeetCode ↗
02

Intuition

Each list is sorted, so the smallest node that has not been used yet is always at the front of some list. The next node of the answer is simply the smallest of the k current fronts.

  • Find: a min-heap holding one front node per list gives the smallest in O(log k) instead of comparing all k.
  • Advance: when a node is taken, the node after it in the same list becomes that list's new front, so it goes into the heap.

The heap never holds more than k nodes, and each of the N nodes (all lists together) goes in and comes out once, so the whole merge costs O(N log k).

How to spot this pattern

Use a heap of size k whenever you repeatedly need the smallest (or largest) item across k sorted sequences: merging k sorted lists or arrays, the kth smallest in a sorted matrix, or the smallest range covering k lists.

03

Approach

Try it first

Before reading on: you know how to merge two sorted lists with two pointers. With k lists, which nodes can possibly be the next one in the answer? How would you find the smallest of them quickly, again and again?

1

Put every non-empty list's first node in a min-heap

Each heap entry is (value, list index, node). The index is a tiebreaker: on equal values the heap compares indices, so it never has to compare two nodes.

2

Start the answer behind a dummy node

Create a placeholder dummy and a pointer tail to it. Every node is then attached the same way, with tail.next = node, so the first node needs no special case.

3

Pop the smallest node and attach it

Pop the top entry, set tail.next = node, and move tail to it. It is the smallest unused node, because every other unused node sits behind one of the fronts in the heap, and those fronts are no smaller than it.

4

Push the next node from the same list

If node.next exists, push it with the same list index. That list now has a new front, and it must be in the heap to compete for the next spot.

5

Return the merged list

When the heap is empty, every node has been attached in order. Return dummy.next, the first real node; dummy itself is not part of the answer.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]:
▶3 heap = [(node.val, i, node) for i, node in enumerate(lists) if node]
▶4 heapq.heapify(heap)
▶5 dummy = tail = ListNode(0)
▶6 while heap:
▶7 val, i, node = heapq.heappop(heap)
▶8 tail.next = node
▶9 tail = node
▶10 if node.next:
▶11 heapq.heappush(heap, (node.next.val, i, node.next))
▶12 return dummy.next
list 01front45list 11front34list 22front6heap1list 01list 12list 2mergedddummyheap ← first node of each non-empty list
k3lists
heap1 (list 0), 1 (list 1), 2 (list 2)smallest on top
Start. Every list is sorted, so the smallest unused node is always one of the list fronts. Each front goes into the min-heap as (value, list index, node).
list 045list 11front34list 22front6heap1list 12list 2mergedd1taildummypop 1 from list 0 → tail.next
popped1from list 0
merged[1]
Pop 1. It is the smallest front, so no unused node anywhere is smaller. Attach it after the tail and move the tail onto it. Another front also holds 1; the smaller list index (0) broke the tie, so the nodes themselves were never compared.
list 04front5list 11front34list 22front6heap1list 12list 24list 0mergedd1taildummypush 4, the next node of list 0
pushed4new front of list 0
heap1 (list 1), 2 (list 2), 4 (list 0)3 of at most 3
List 0 has a new front, 4. It goes into the heap so it can compete for the next spot. The heap still holds at most one node per list.
list 04front5list 134list 22front6heap2list 24list 0mergedd11taildummypop 1 from list 1 → tail.next
popped1from list 1
merged[1, 1]
Pop 1. It is the smallest front, so no unused node anywhere is smaller. Attach it after the tail and move the tail onto it.
list 04front5list 13front4list 22front6heap2list 23list 14list 0mergedd11taildummypush 3, the next node of list 1
pushed3new front of list 1
heap2 (list 2), 3 (list 1), 4 (list 0)3 of at most 3
List 1 has a new front, 3. It goes into the heap so it can compete for the next spot. The heap still holds at most one node per list.
list 04front5list 13front4list 26heap3list 14list 0mergedd112taildummypop 2 from list 2 → tail.next
popped2from list 2
merged[1, 1, 2]
Pop 2. It is the smallest front, so no unused node anywhere is smaller. Attach it after the tail and move the tail onto it.
list 04front5list 13front4list 26frontheap3list 14list 06list 2mergedd112taildummypush 6, the next node of list 2
pushed6new front of list 2
heap3 (list 1), 4 (list 0), 6 (list 2)3 of at most 3
List 2 has a new front, 6. It goes into the heap so it can compete for the next spot. The heap still holds at most one node per list.
list 04front5list 14list 26frontheap4list 06list 2mergedd1123taildummypop 3 from list 1 → tail.next
popped3from list 1
merged[1, 1, 2, 3]
Pop 3. It is the smallest front, so no unused node anywhere is smaller. Attach it after the tail and move the tail onto it.
list 04front5list 14frontlist 26frontheap4list 04list 16list 2mergedd1123taildummypush 4, the next node of list 1
pushed4new front of list 1
heap4 (list 0), 4 (list 1), 6 (list 2)3 of at most 3
List 1 has a new front, 4. It goes into the heap so it can compete for the next spot. The heap still holds at most one node per list.
list 05list 14frontlist 26frontheap4list 16list 2mergedd11234taildummypop 4 from list 0 → tail.next
popped4from list 0
merged[1, 1, 2, 3, 4]
Pop 4. It is the smallest front, so no unused node anywhere is smaller. Attach it after the tail and move the tail onto it. Another front also holds 4; the smaller list index (0) broke the tie, so the nodes themselves were never compared.
list 05frontlist 14frontlist 26frontheap4list 15list 06list 2mergedd11234taildummypush 5, the next node of list 0
pushed5new front of list 0
heap4 (list 1), 5 (list 0), 6 (list 2)3 of at most 3
List 0 has a new front, 5. It goes into the heap so it can compete for the next spot. The heap still holds at most one node per list.
list 05frontlist 1list 26frontheap5list 06list 2mergedd112344taildummypop 4 from list 1 → tail.next
popped4from list 1
merged[1, 1, 2, 3, 4, 4]
Pop 4. It is the smallest front, so no unused node anywhere is smaller. Attach it after the tail and move the tail onto it.
list 0list 1list 26frontheap6list 2mergedd1123445taildummypop 5 from list 0 → tail.next
popped5from list 0
merged[1, 1, 2, 3, 4, 4, 5]
Pop 5. It is the smallest front, so no unused node anywhere is smaller. Attach it after the tail and move the tail onto it.
list 0list 1list 2heapemptymergedd11234456taildummypop 6 from list 2 → tail.next
popped6from list 2
merged[1, 1, 2, 3, 4, 4, 5, 6]
Pop 6. It is the smallest front, so no unused node anywhere is smaller. Attach it after the tail and move the tail onto it.
list 0list 1list 2heapemptymergedd11234456returndummyheap empty → return dummy.next
result[1, 1, 2, 3, 4, 4, 5, 6]8 nodes
Done. Every node was pushed once and popped once, each in O(log k), so the merge took O(N log k). The answer starts at dummy.next; the dummy itself was only a starting point.
05

Merge pairs in rounds (divide and conquer)

With step = 1, merge lists[i] with lists[i + step] for every i that is a multiple of 2 * step, and store the result in lists[i]. Double step and repeat; after about log k rounds the whole answer is in lists[0].

▶1class Solution:
▶2 def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]:
▶3 if not lists:
▶4 return None
▶5 step = 1
▶6 while step < len(lists):
▶7 for i in range(0, len(lists) - step, step * 2):
▶8 lists[i] = self.mergeTwo(lists[i], lists[i + step])
▶9 step *= 2
▶10 return lists[0]
▶11 
▶12 def mergeTwo(self, a, b):
▶13 dummy = tail = ListNode(0)
▶14 while a and b:
▶15 if a.val <= b.val:
▶16 tail.next, a = a, a.next
▶17 else:
▶18 tail.next, b = b, b.next
▶19 tail = tail.next
▶20 tail.next = a or b
▶21 return dummy.next
06

Common pitfalls

Leaving out the tiebreaker in Python

✗ Wrong
heap = [(node.val, node) for node in lists if node]
✓ Right
heap = [(node.val, i, node) for i, node in enumerate(lists) if node]

In Python, two equal values make heapq compare the next tuple item. ListNode has no <, so it raises TypeError. The list index is unique, so ties are settled before a node is compared.

Pushing every node at the start

✗ Wrong
heap = [(n.val, i, n) for i, head in enumerate(lists)
        for n in walk(head)]
✓ Right
heap = [(node.val, i, node) for i, node in enumerate(lists) if node]
# push node.next only after node is popped

The answer is still right, but the heap grows to N entries, so it costs O(N) memory and each operation O(log N). One front per list keeps it at k.

Merging the lists one after another

✗ Wrong
result = None
for head in lists:
    result = merge_two(result, head)
✓ Right
# heap of fronts, or merge pairs in rounds

Each merge walks the whole growing result again, so early nodes are copied about k times: O(N·k) in total, which is too slow when k and N are both near 10⁴.

07

Edge cases

No lists, or only empty lists

Nothing goes into the heap, the loop never runs, and dummy.next is null, which is the correct empty answer for [] and [[]].

08

Complexity

Time
O(N log k)
Space
O(k)
N is the total number of nodes. Each node is pushed and popped once, and each heap operation costs O(log k) because the heap holds at most one node per list. The output reuses the input nodes, so the only extra memory is the heap.
09

Merge K Sorted Lists FAQ

What are the steps?
  • Heap: put the first node of every non-empty list into a min-heap, keyed by value.
  • Repeat: pop the smallest node, attach it to the answer, and push its next if there is one.
  • Answer: when the heap is empty, return the node after the dummy.
  • Complexity: O(N log k) time, O(k) extra space.
Why is it rated Hard?

Merging is easy; doing it fast is the hard part. Comparing all k fronts for every node, or merging lists one after another, is O(N·k). You have to see that a heap, or merging in pairs, brings it down to O(N log k).