Merge k Sorted Lists
Merge k Sorted Lists is a hard heaps problem solved with the merge k sorted pattern.
The best approach, optimal (min-heap of heads), runs in O(N log k) time and O(k) space.
Below are 2 approaches in Java, Python, C++ and JavaScript, from merge one list at a time up.
Problem
Given an array of k sorted linked lists, merge them into one sorted linked list and return its head.
Examples
Example 1
- Input
lists = [[1, 4, 5], [1, 3, 4], [2, 6]]- Output
[1, 1, 2, 3, 4, 4, 5, 6]
Example 2
- Input
lists = [[], []]- Output
[]
Constraints
0 <= k <= 10^4; total nodes N up to10^4.- Each list is sorted.
Solve it here
Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.
Your own testcases: Run checks these, and the expected output comes from our reference solution.
My submissions
Nothing yet. Every Run and Submit you make while signed in shows up here.
| When | Result | Tests | Runtime | Your time | Type |
|---|
Run checks the testcases above (2 examples, or your own). Submit also runs 10 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.
Animated walkthrough
A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
Solutions
Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.
| Approach | Time | Space |
|---|---|---|
| Merge one list at a time | O(k · N) | O(1) |
| Optimal (min-heap of heads) | O(N log k) | O(k) |
1Merge one list at a time
O(k · N)The growing result is re-walked for every list.O(1)Merge list 0 with list 1, then the result with list 2, and so on.
- result = null; for each list: result = mergeTwo(result, list).
class Solution {
public ListNode mergeKLists(ListNode[] lists) {
ListNode result = null;
for (ListNode l : lists) result = merge(result, l);
return result;
}
private ListNode merge(ListNode a, ListNode b) {
ListNode dummy = new ListNode(), t = dummy;
while (a != null && b != null) {
if (a.val <= b.val) { t.next = a; a = a.next; } else { t.next = b; b = b.next; }
t = t.next;
}
t.next = a != null ? a : b;
return dummy.next;
}
}class Solution:
def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]:
result = None
for l in lists:
result = self.merge(result, l)
return result
def merge(self, a: Optional[ListNode], b: Optional[ListNode]) -> Optional[ListNode]:
dummy = ListNode()
t = dummy
while a and b:
if a.val <= b.val:
t.next = a
a = a.next
else:
t.next = b
b = b.next
t = t.next
t.next = a if a else b
return dummy.nextclass Solution {
public:
ListNode* mergeKLists(vector<ListNode*>& lists) {
ListNode* result = nullptr;
for (ListNode* l : lists) result = merge(result, l);
return result;
}
private:
ListNode* merge(ListNode* a, ListNode* b) {
ListNode dummy;
ListNode* t = &dummy;
while (a && b) {
if (a->val <= b->val) { t->next = a; a = a->next; } else { t->next = b; b = b->next; }
t = t->next;
}
t->next = a ? a : b;
return dummy.next;
}
};function mergeKLists(lists) {
let result = null;
for (const l of lists) result = merge(result, l);
return result;
}
function merge(a, b) {
const dummy = new ListNode();
let t = dummy;
while (a !== null && b !== null) {
if (a.val <= b.val) { t.next = a; a = a.next; } else { t.next = b; b = b.next; }
t = t.next;
}
t.next = a !== null ? a : b;
return dummy.next;
}2Optimal (min-heap of heads)
O(N log k)O(k)Put the head of each non-empty list in a min-heap. Repeatedly poll the smallest, append it, and push its next node.
- Offer all non-null heads.
- While the heap is not empty: n = poll(); tail.next = n; if n.next != null offer(n.next).
class Solution {
public ListNode mergeKLists(ListNode[] lists) {
PriorityQueue<ListNode> heap = new PriorityQueue<>((a, b) -> Integer.compare(a.val, b.val));
for (ListNode l : lists) if (l != null) heap.offer(l);
ListNode dummy = new ListNode(), tail = dummy;
while (!heap.isEmpty()) {
ListNode n = heap.poll();
tail.next = n;
tail = n;
if (n.next != null) heap.offer(n.next);
}
return dummy.next;
}
}class Solution:
def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]:
heap = [] # (val, tie-breaker, node)
for i, l in enumerate(lists):
if l:
heapq.heappush(heap, (l.val, i, l))
dummy = ListNode()
tail = dummy
while heap:
_, i, n = heapq.heappop(heap)
tail.next = n
tail = n
if n.next:
heapq.heappush(heap, (n.next.val, i, n.next))
return dummy.nextclass Solution {
public:
ListNode* mergeKLists(vector<ListNode*>& lists) {
auto cmp = [](ListNode* a, ListNode* b) { return a->val > b->val; };
priority_queue<ListNode*, vector<ListNode*>, decltype(cmp)> heap(cmp);
for (ListNode* l : lists) if (l) heap.push(l);
ListNode dummy;
ListNode* tail = &dummy;
while (!heap.empty()) {
ListNode* n = heap.top();
heap.pop();
tail->next = n;
tail = n;
if (n->next) heap.push(n->next);
}
return dummy.next;
}
};class MinHeap {
constructor(cmp = (a, b) => a - b) { this.a = []; this.cmp = cmp; }
size() { return this.a.length; }
isEmpty() { return this.a.length === 0; }
peek() { return this.a[0]; }
push(x) {
const a = this.a;
a.push(x);
let i = a.length - 1;
while (i > 0) {
const p = (i - 1) >> 1;
if (this.cmp(a[i], a[p]) >= 0) break;
[a[i], a[p]] = [a[p], a[i]];
i = p;
}
}
pop() {
const a = this.a, top = a[0], last = a.pop();
if (a.length > 0) {
a[0] = last;
let i = 0;
while (true) {
const l = 2 * i + 1, r = l + 1;
let m = i;
if (l < a.length && this.cmp(a[l], a[m]) < 0) m = l;
if (r < a.length && this.cmp(a[r], a[m]) < 0) m = r;
if (m === i) break;
[a[i], a[m]] = [a[m], a[i]];
i = m;
}
}
return top;
}
}
function mergeKLists(lists) {
const heap = new MinHeap((a, b) => a.val - b.val);
for (const l of lists) if (l !== null) heap.push(l);
const dummy = new ListNode();
let tail = dummy;
while (!heap.isEmpty()) {
const n = heap.pop();
tail.next = n;
tail = n;
if (n.next !== null) heap.push(n.next);
}
return dummy.next;
}Edge cases to test
- Empty lists inside the array
- k = 0
Hints
Hint 1
The next node of the answer is always the smallest current head. A min-heap finds it in O(log k).
FAQ
What is the best time complexity for Merge k Sorted Lists?
Optimal (min-heap of heads) runs in O(N log k) time and O(k) extra space.
Which pattern does Merge k Sorted Lists use?
It is a heaps problem that uses the merge k sorted pattern. Other problems with the same pattern: Merge k Sorted Arrays, Design Twitter, Smallest Range Covering Elements from K Lists.
Is there a brute force solution for Merge k Sorted Lists?
Yes. Merge one list at a time takes O(k · N) time and O(1) space. Merge list 0 with list 1, then the result with list 2, and so on.
Which edge cases should I test for Merge k Sorted Lists?
Empty lists inside the array; k = 0.