Merge K Sorted Lists
Your code isn't saved yet: refreshing or leaving the page resets it. Saved progress comes with user accounts.
You're given an array lists of k linked lists, each sorted in ascending order. Merge them all into one sorted linked list and return its head.
Understand the problem
This is Merge Two Sorted Lists, but with k lists instead of two. (If you haven't solved that one, start there: this problem builds on it.)
- Every input list is already sorted from smallest to largest.
- The result must contain every node from every list, in sorted order.
- Some lists may be empty, and
listsitself may be empty.
Example 1
Input: lists = [[1, 4, 5], [1, 3, 4], [2, 6]]
Output: [1, 1, 2, 3, 4, 4, 5, 6]Three sorted lists become one sorted list of all eight values.
Example 2
Input: lists = []
Output: []No lists at all, so the result is empty.
Example 3
Input: lists = [[]]
Output: []One list, and it's empty.
Constraints
0 <= k <= 10^40 <= lists[i].length <= 500- The total number of nodes is at most
10^4.
Hints
Stuck? Open one hint at a time. Each one gives away a little more than the last.
The idea in one sentence
Merge the lists in pairs, round after round (like a tournament bracket), reusing the two-list merge, until only one list is left.
The naive approach (and why it's slow)
Merge them one after another: result = merge(result, lists[i]) for each list.
The problem is that result keeps growing, and every merge walks through all of it again. If there are k lists with N nodes in total, the early nodes get re-walked about k times, for roughly O(N · k). With 10,000 lists, that's very slow.
The key insight
Approach 1: divide and conquer (the JS/TS solution). Merge in pairs, like the rounds of a tournament:
- Round 1:
klists becomek/2. - Round 2:
k/2becomek/4. And so on, until one is left.
Each round touches every node once (each node is in exactly one pair), and halving k until it reaches 1 takes about log k rounds. Total: O(N log k). Best of all, it reuses Merge Two Sorted Lists without changes.
Approach 2: a min-heap (the Python solution). A min-heap is a structure that hands you its smallest item in O(log size). Put the front node of every list into it. Then repeatedly: pop the smallest node, attach it to the result, and push that node's next (if any). The heap never holds more than k nodes. Also O(N log k). (Heaps have their own category later on.)
Step by step (divide and conquer)
lists = [[1, 4, 5], [1, 3, 4], [2, 6]]:
| Round | Lists going in | Pairs merged | Lists coming out |
|---|---|---|---|
| 1 | [1,4,5], [1,3,4], [2,6] | [1,4,5] + [1,3,4]; [2,6] has no partner | [1,1,3,4,4,5], [2,6] |
| 2 | [1,1,3,4,4,5], [2,6] | [1,1,3,4,4,5] + [2,6] | [1,1,2,3,4,4,5,6] |
One list left: that's the answer.
When a list has no partner (an odd count), merge it with an empty list, which just returns it unchanged.
The code
The reference solution is below, with comments on every important line. JavaScript and TypeScript use divide and conquer (JavaScript has no built-in heap); Python uses its built-in heapq min-heap.
How fast is it?
With N total nodes and k lists:
- Time: O(N log k) for both approaches.
- Memory: O(k) for the list of lists in each round, or O(k) for the heap.
Common mistakes
- Merging one by one. Correct, but O(N · k), which times out with many lists.
- Forgetting empty input.
lists = []must returnnull, not crash onround[0]. - Python heaps and ties. If two nodes have the same value,
heapqtries to compare the nodes themselves and crashes. Push(value, index, node): the unique index breaks ties.
Going deeper
- This problem is the "merge" half of merge sort, generalized to many inputs. It's also how databases and search engines merge many sorted files (an "external merge sort").
- Approach 2 is the better choice when the lists are streams you can't hold in memory: the heap only ever needs the current front of each one.
Reference solution
// Merge Two Sorted Lists, unchanged: always attach the smaller front node.
function mergeTwo(a, b) {
const dummy = new ListNode()
let tail = dummy
while (a && b) {
if (a.val <= b.val) {
tail.next = a
a = a.next
} else {
tail.next = b
b = b.next
}
tail = tail.next
}
tail.next = a ?? b // attach whatever is left
return dummy.next
}
/**
* @param {Array<ListNode | null>} lists
* @return {ListNode | null}
*/
export default function mergeKLists(lists) {
if (lists.length === 0) return null
let round = lists
// Each round merges the lists in pairs, halving how many are left (like a tournament).
while (round.length > 1) {
const next = []
for (let i = 0; i < round.length; i += 2) {
// With an odd count, the last list has no partner: merging with null keeps it as is.
next.push(mergeTwo(round[i], round[i + 1] ?? null))
}
round = next
}
return round[0]
}// Merge Two Sorted Lists, unchanged: always attach the smaller front node.
function mergeTwo(a: ListNode | null, b: ListNode | null): ListNode | null {
const dummy = new ListNode()
let tail = dummy
while (a && b) {
if (a.val <= b.val) {
tail.next = a
a = a.next
} else {
tail.next = b
b = b.next
}
tail = tail.next
}
tail.next = a ?? b // attach whatever is left
return dummy.next
}
export default function mergeKLists(lists: Array<ListNode | null>): ListNode | null {
if (lists.length === 0) return null
let round = lists
// Each round merges the lists in pairs, halving how many are left (like a tournament).
while (round.length > 1) {
const next: Array<ListNode | null> = []
for (let i = 0; i < round.length; i += 2) {
// With an odd count, the last list has no partner: merging with null keeps it as is.
next.push(mergeTwo(round[i], round[i + 1] ?? null))
}
round = next
}
return round[0]
}import heapq
def merge_k_lists(lists: list[ListNode | None]) -> ListNode | None:
# A min-heap of the front node of every non-empty list. heappop always gives the smallest.
# The index i breaks ties, so Python never has to compare two ListNode objects.
heap = [(node.val, i, node) for i, node in enumerate(lists) if node]
heapq.heapify(heap)
dummy = ListNode() # fake first node, as in Merge Two Sorted Lists
tail = dummy
while heap:
# Take the smallest front node of all the lists and attach it.
_, i, node = heapq.heappop(heap)
tail.next = node
tail = node
# That list's next node is now its front: put it in the heap.
if node.next:
heapq.heappush(heap, (node.next.val, i, node.next))
return dummy.next