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.
kcan be 0, and any list can be empty.- There are at most 10⁴ nodes in total, but
kcan also be 10⁴, so scanning allkheads for every node can reach 10⁸ steps.
- 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⁴
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).
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.
Approach
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?
Two ways to solve it
A heap keeps one front node per list and hands out the smallest each time.
- Node moves: each node is attached exactly once.
- Memory: the heap, up to k entries.
- Fits: lists of very different lengths, or lists that arrive over time.
The answer most interviewers expect.
Merge lists 0 and 1, 2 and 3, and so on; then merge the results in pairs again until one list is left.
- Node moves: each node is passed along about log k times.
- Memory: no extra structure, only pointers.
- Fits: when a heap is not available.
Same speed, a little more code.
Both run in O(N log k). The heap version is the one interviewers usually look for and attaches every node only once; merging in pairs saves the heap's memory. The steps, code and live demo follow the heap; the pairwise code comes after the demo.
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.
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.
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.
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.
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.
Code in Python, C++ and Java
dummy.next; the dummy itself was only a starting point.dummy.next; the dummy itself was only a starting point.dummy.next; the dummy itself was only a starting point.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].
Common pitfalls
Leaving out the tiebreaker in Python
heap = [(node.val, node) for node in lists if node]
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
heap = [(n.val, i, n) for i, head in enumerate(lists)
for n in walk(head)]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
result = None
for head in lists:
result = merge_two(result, head)# 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⁴.
Edge cases
Nothing goes into the heap, the loop never runs, and dummy.next is null, which is the correct empty answer for [] and [[]].
Complexity
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
nextif 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).