Try it first — give it 40 minutes
0/4 revealedStuck? Take one hint at a time. The struggle is where the pattern sticks.
The problem in plain English
You get an array lists of k linked lists. Each list is sorted in ascending order. Merge them all into one sorted linked list and return its head.
k can be 0. Any list can be empty. Let N be the total number of nodes across all lists.
Example: lists = [[1, 4, 5], [1, 3, 4], [2, 6]] → [1, 1, 2, 3, 4, 4, 5, 6].
Start with brute force
Option A: dump every value into an array, sort it, and build a new list. That's O(N log N), and it ignores the fact that the lists were already sorted.
Option B: merge the lists one at a time, the way you did in Merge Two Sorted Lists: merge list 1 into list 2, that result into list 3, and so on. It's correct, but the merged list keeps growing, and you walk it again for every new list. With k lists of n nodes each, that's n + 2n + 3n + … + kn, which is about k²n / 2 steps. For k = 10⁴ lists of 50 nodes, that's 2.5 billion steps.
Building the intuition
This Hard is two Medium ideas stacked together: merging two sorted lists (Linked Lists stage) and "keep the smallest of many things handy" (Heaps & Greedy stage).
Start with what you know. In Merge Two Sorted Lists, you look at two heads and take the smaller one. Now imagine k heads lined up:
list 0: [1] → 4 → 5
list 1: [1] → 3 → 4
list 2: [2] → 6The first node of the answer must be one of the bracketed heads. Nothing deeper in a list can be smaller than its own head. So the answer's next node is the minimum of the k heads. Take it. Its list now has a new head, so look at the k heads again.
Done naively, "find the minimum of k heads" is a scan of k items for each of the N nodes. That's O(N·k). But look at how the set of heads changes. Each step removes one item (the smallest) and adds one item (its successor). "Give me the minimum, then let me insert something" is exactly what a min-heap does, in O(log k) per operation.
There's a second route to the same speed: divide and conquer. Merge the lists in pairs (0 with 1, 2 with 3, …), then merge those results in pairs, and so on. There are log k rounds, and each round touches every node once. That also gives O(N log k). We show the heap version in code because it's the one you'll reuse most often (see Find Median from Data Stream). The pairwise version is a good follow-up answer.
The optimal approach
- Push the head of every non-empty list into a min-heap ordered by
val. - Make a dummy node and a
tailpointer to it, so attaching the first real node needs no special case. - While the heap isn't empty:
- pop the smallest node and attach it:
tail.next = node; tail = node; - if
node.nextexists, push it. That list's next candidate is now in the heap.
- pop the smallest node and attach it:
- Return
dummy.next.
The subtle detail: ties in Python. heapq compares tuples element by element. If two nodes have the same val, Python would compare the next element, the ListNodes, and crash, because ListNode has no <. So we push (val, i, node), where i is the list's index. Two entries never share both val and i, so the comparison never reaches the node. Java and C++ take a comparator, and JavaScript has no built-in heap, so the JS solution includes a small MinHeap class.
We reuse the original nodes. We only rewire next pointers and never allocate a new node, so the extra space is just the heap.
The code
Every solution below is tested against the examples and edge cases before it ships. Pick your language — we'll remember it.
import heapq
class Solution:
def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]:
# The heap holds the current head of every list: at most k nodes at a time.
# The index i breaks ties so Python never tries to compare two ListNodes.
heap = []
for i, node in enumerate(lists):
if node:
heap.append((node.val, i, node))
heapq.heapify(heap)
dummy = tail = ListNode() # dummy head: no special case for the first node
while heap:
_, i, node = heapq.heappop(heap) # smallest head across all lists
tail.next = node
tail = node
if node.next: # that list's next node is now its head
heapq.heappush(heap, (node.next.val, i, node.next))
return dummy.nextclass Solution {
public:
ListNode* mergeKLists(vector<ListNode*>& lists) {
// priority_queue is a max-heap by default; flip the comparison to pop the smallest val.
auto bigger = [](ListNode* a, ListNode* b) { return a->val > b->val; };
priority_queue<ListNode*, vector<ListNode*>, decltype(bigger)> heap(bigger);
// The heap holds the current head of every list: at most k nodes at a time.
for (ListNode* node : lists)
if (node) heap.push(node);
ListNode dummy; // dummy head: no special case for the first node
ListNode* tail = &dummy;
while (!heap.empty()) {
ListNode* node = heap.top(); // smallest head across all lists
heap.pop();
tail->next = node;
tail = node;
if (node->next) heap.push(node->next); // that list's next node is now its head
}
return dummy.next;
}
};class Solution {
public ListNode mergeKLists(ListNode[] lists) {
// Min-heap ordered by val. It holds the current head of every list: at most k nodes.
PriorityQueue<ListNode> heap = new PriorityQueue<>((a, b) -> Integer.compare(a.val, b.val));
for (ListNode node : lists)
if (node != null) heap.offer(node);
ListNode dummy = new ListNode(); // dummy head: no special case for the first node
ListNode tail = dummy;
while (!heap.isEmpty()) {
ListNode node = heap.poll(); // smallest head across all lists
tail.next = node;
tail = node;
if (node.next != null) heap.offer(node.next); // that list's next node is now its head
}
return dummy.next;
}
}// JavaScript has no built-in heap, so here is a small binary min-heap.
// less(a, b) says whether a should come out before b.
class MinHeap {
constructor(less) {
this.less = less;
this.items = [];
}
size() {
return this.items.length;
}
push(x) {
const a = this.items;
a.push(x);
let i = a.length - 1;
while (i > 0) { // sift up: swap with the parent while we beat it
const p = (i - 1) >> 1;
if (!this.less(a[i], a[p])) break;
[a[i], a[p]] = [a[p], a[i]];
i = p;
}
}
pop() {
const a = this.items;
const top = a[0];
const last = a.pop();
if (a.length > 0) {
a[0] = last;
let i = 0;
while (true) { // sift down: swap with the smaller child while it beats us
const l = 2 * i + 1, r = l + 1;
let best = i;
if (l < a.length && this.less(a[l], a[best])) best = l;
if (r < a.length && this.less(a[r], a[best])) best = r;
if (best === i) break;
[a[i], a[best]] = [a[best], a[i]];
i = best;
}
}
return top;
}
}
/**
* @param {ListNode[]} lists
* @return {ListNode}
*/
var mergeKLists = function (lists) {
// The heap holds the current head of every list: at most k nodes at a time.
const heap = new MinHeap((a, b) => a.val < b.val);
for (const node of lists) if (node) heap.push(node);
const dummy = new ListNode(); // dummy head: no special case for the first node
let tail = dummy;
while (heap.size() > 0) {
const node = heap.pop(); // smallest head across all lists
tail.next = node;
tail = node;
if (node.next) heap.push(node.next); // that list's next node is now its head
}
return dummy.next;
};Dry run
lists = [[1, 4, 5], [1, 3, 4], [2, 6]]. Heap entries are written value (list).
| Step | Heap before pop | Pop | Push | Result so far |
|---|---|---|---|---|
| start | 1(0), 1(1), 2(2) | — | — | — |
| 1 | 1(0), 1(1), 2(2) | 1(0) | 4(0) | 1 |
| 2 | 1(1), 2(2), 4(0) | 1(1) | 3(1) | 1 1 |
| 3 | 2(2), 3(1), 4(0) | 2(2) | 6(2) | 1 1 2 |
| 4 | 3(1), 4(0), 6(2) | 3(1) | 4(1) | 1 1 2 3 |
| 5 | 4(0), 4(1), 6(2) | 4(0) | 5(0) | 1 1 2 3 4 |
| 6 | 4(1), 5(0), 6(2) | 4(1) | — (end of list 1) | 1 1 2 3 4 4 |
| 7 | 5(0), 6(2) | 5(0) | — | … 5 |
| 8 | 6(2) | 6(2) | — | 1 1 2 3 4 4 5 6 |
The heap never holds more than 3 entries, one per list.
Complexity
- Time: O(N log k). Every one of the
Nnodes is pushed once and popped once. Each heap operation costs O(log k) because the heap holds at mostkentries. Building the first heap is O(k). - Space: O(k) for the heap. The output reuses the input nodes.
Edge cases and traps
listsis empty, or every list is empty. The heap starts empty, the loop never runs, anddummy.nextisnull. That's correct.- Pushing
null. Skip empty lists when you seed the heap, and only pushnode.nextwhen it exists. Anullin the heap crashes the comparator. - Python tuple ties. Without the index in
(val, i, node), equal values makeheapqcompare twoListNodes and raise aTypeError. - Max-heap by accident in C++.
priority_queuepops the largest by default. The comparator must bea->val > b->valto get a min-heap. - Pushing whole lists up front. Some students push every node into the heap at the start. That works, but it's O(N log N) time and O(N) space, which throws away the sortedness.
Say it in the interview
"The next node of the merged list is always the smallest of the k current heads. Scanning k heads per node is O(N·k). Instead, I keep the heads in a min-heap. I pop the smallest, attach it behind a dummy node, and push its successor. Each node goes in and out of the heap once, at O(log k) each, so that's O(N log k) time and O(k) space. I reuse the original nodes, so nothing new gets allocated."
Follow-ups interviewers ask
- "Can you do it without a heap?" Yes: divide and conquer. Merge lists in pairs, then merge the results in pairs. That's
log krounds, and each round touches allNnodes, so O(N log k) time. Done bottom-up with an interval that doubles each round, it uses O(1) extra space. - "The lists are too big for memory: they're sorted files on disk." Same heap, but keep one read cursor per file. This is the k-way merge step of external sort.
- "Return only the k-th smallest overall." Stop after
kpops. It's the same pattern as Kth Largest Element in an Array, with sorted inputs.
Practise the same idea
This is a bonus day of the free DSA plan 🐸
90 problems in the order that builds on itself, one a day, with a walkthrough like this for each. Tick them off and keep your streak.
Get the full roadmap — free