Merge K Sorted Lists
Hard · Linked lists
Jump to codeMerge k ascending singly linked lists into one ascending list. Inputs may contain empty lists.
Examples
Example 1
lists = [[1,4,5],[1,3,4],[2,6]]
Output: [1,1,2,3,4,4,5,6]
Example 2
lists = []
Output: []
Constraints
- k == lists.length
- 0 <= k <= 10^4
- 0 <= lists[i].length <= 500
- -10^4 <= lists[i][j] <= 10^4
- lists[i] is sorted in ascending order.
- The sum of lists[i].length will not exceed 10^4.
Function contract
Linked lists are displayed as value arrays. Your code receives ListNode objects with val and next fields.
Need a hint?
Only the head of each remaining list can be the next smallest node.
Asked in real interviews
Candidates reported versions of Merge K Sorted Lists from these company interviews. Some company questions are locked and open with Premium or XP.
Browse all real coding interview questionsSolution approach
Put each nonempty head in a min-heap with a tie-breaking counter so equal values do not compare node objects. Pop the smallest node, append it, and push its successor. Repeat until the heap is empty.
Complexity
O(N log k) time and O(k) auxiliary space for N total nodes (k ≥ 2).
Python reference solution
import heapq
def mergeKLists(lists):
heap = []
for index, node in enumerate(lists):
if node:
heapq.heappush(heap, (node.val, index, node))
dummy = ListNode()
tail = dummy
while heap:
_, index, node = heapq.heappop(heap)
tail.next = node
tail = node
if node.next:
heapq.heappush(heap, (node.next.val, index, node.next))
return dummy.next
JavaScript solution
// Binary heap: comesBefore(a, b) decides which item has higher priority.
class Heap {
constructor(comesBefore) { this.items = []; this.comesBefore = comesBefore; }
get size() { return this.items.length; }
peek() { return this.items[0]; }
push(value) {
const a = this.items;
a.push(value);
let i = a.length - 1;
while (i > 0) {
const parent = Math.floor((i - 1) / 2);
if (!this.comesBefore(a[i], a[parent])) break;
[a[i], a[parent]] = [a[parent], a[i]];
i = parent;
}
}
pop() {
const a = this.items, result = a[0], last = a.pop();
if (!a.length) return result;
a[0] = last;
let i = 0;
while (2 * i + 1 < a.length) {
let child = 2 * i + 1;
if (child + 1 < a.length && this.comesBefore(a[child + 1], a[child])) child++;
if (!this.comesBefore(a[child], a[i])) break;
[a[i], a[child]] = [a[child], a[i]];
i = child;
}
return result;
}
}
function mergeKLists(lists) {
const heap = new Heap((a, b) => a.val < b.val);
for (const node of lists) if (node) heap.push(node);
const dummy = new ListNode();
let tail = dummy;
while (heap.size) {
const node = heap.pop();
tail.next = node; tail = node;
if (node.next) heap.push(node.next);
}
return dummy.next;
}
Java solution
import java.util.*;
class Solution {
public ListNode mergeKLists(ListNode[] lists) {
PriorityQueue<ListNode> heap = new PriorityQueue<>(Comparator.comparingInt(node -> node.val));
for (ListNode node : lists) if (node != null) heap.add(node);
ListNode dummy = new ListNode(), tail = dummy;
while (!heap.isEmpty()) {
ListNode node = heap.remove();
tail.next = node; tail = node;
if (node.next != null) heap.add(node.next);
}
return dummy.next;
}
}
C++ solution
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
ListNode* mergeKLists(vector<ListNode*> &lists) {
auto later = [](ListNode* a, ListNode* b) { return a->val > b->val; };
priority_queue<ListNode*, vector<ListNode*>, decltype(later)> heap(later);
for (ListNode* node : lists) if (node) heap.push(node);
ListNode dummy;
ListNode* tail = &dummy;
while (!heap.empty()) {
ListNode* node = heap.top(); heap.pop();
tail->next = node; tail = node;
if (node->next) heap.push(node->next);
}
return dummy.next;
}
};
Trace a boundary case, then implement the approach in the editor. Submit checks your solution against all 8 test cases.
Keep your reasoning, pseudocode, and edge cases here.
Notes stay in this browser when storage is available.
Accepted submissions mark this problem complete. Progress stays in this browser.
[
[
[
1,
4,
5
],
[
1,
3,
4
],
[
2,
6
]
]
][ 1, 1, 2, 3, 4, 4, 5, 6 ]
[ [] ]
[]
[
[
[]
]
][]
[
[
[
1,
2,
2
],
[
1,
1,
2
]
]
][ 1, 1, 1, 2, 2, 2 ]
[
[
[
-1,
0,
1
],
[],
[
2
]
]
][ -1, 0, 1, 2 ]
Drafts are saved per language in this browser when storage is available.