Merge k Sorted Lists solution explained
To merge k sorted linked lists, keep a min-heap holding the current head of each list, repeatedly pop the smallest node, append it to the result and push that node's successor. With N nodes in total this takes O(N log k) time and O(k) extra memory. Merging the lists in pairs, round after round, reaches the same O(N log k) bound without a heap.
By Evin JohnPublished 6 min read
The problem in plain words
You get an array of k linked lists. Every list is sorted from smallest to largest, and some may be empty. Produce a single linked list containing every node from every input, still in ascending order. Reusing the existing nodes is expected; you do not need to copy them.
| Input lists | Merged result |
|---|---|
| [2 → 9], [empty], [1 → 4 → 10], [3] | 1 → 2 → 3 → 4 → 9 → 10 |
| [5 → 5], [5] | 5 → 5 → 5 |
| no lists at all | empty list |
| [−3 → 0 → 8] | −3 → 0 → 8 (one list is already the answer) |
Why it gets asked
It joins two ideas interviewers care about: merging sorted sequences, which you know from merge sort, and choosing a data structure that answers 'what is the smallest of these k things' quickly. It also scales naturally into a design conversation, because merging sorted streams is how log files, search index segments and database sort steps get combined.
Follow-ups
- The inputs are arrays, not lists. Store (value, which array, index) in the heap instead of nodes.
- The data does not fit in memory. External merge: read a buffer from each sorted file and keep a heap of the buffer heads.
- Return only the first m values. Stop after m pops; the cost becomes O(k + m log k).
- Remove duplicates while merging. Skip a popped value equal to the last appended one.
Slower answers first
Collecting every value and sorting is correct and short. It costs O(N log N), and it throws away the useful fact that the inputs are already ordered. Merging list 1 with list 2, then the result with list 3, and so on is closer, but early nodes get walked again in every round; with k lists of similar length the total is about O(N k).
def merge_by_sorting(lists):
values = []
for node in lists:
while node:
values.append(node.val)
node = node.next
sentinel = Node(0)
tail = sentinel
for v in sorted(values):
tail.next = Node(v)
tail = tail.next
return sentinel.nextA min-heap of list heads
At any moment the next node of the answer must be one of the k current heads. A min-heap keeps those heads ordered so the smallest is available in O(log k). Pop it, attach it to the result, and if it has a successor, push the successor. Each of the N nodes is pushed and popped once.
import heapq
class Node:
def __init__(self, val, next=None):
self.val = val
self.next = next
def merge_k_lists(lists):
heap = []
for i, node in enumerate(lists):
if node:
heap.append((node.val, i, node)) # i breaks ties so nodes are never compared
heapq.heapify(heap)
sentinel = Node(0)
tail = sentinel
while heap:
_, i, node = heapq.heappop(heap)
tail.next = node
tail = node
if node.next:
heapq.heappush(heap, (node.next.val, i, node.next))
return sentinel.nextThe index in each tuple matters. When two values are equal, Python compares the next tuple element, and comparing two Node objects raises an error. The list index is unique, so ties are settled before Python ever looks at the nodes.
Pairwise merging, no heap needed
JavaScript has no built-in priority queue, so the divide-and-conquer route is often easier there. Merge lists in pairs: 0 with 1, 2 with 3, and so on. That halves the number of lists. Repeat until one remains. Each round touches every node once and there are about log k rounds, so the total is again O(N log k), with O(1) extra memory beyond the array of lists.
class ListNode {
constructor(val, next = null) {
this.val = val;
this.next = next;
}
}
function mergeTwo(a, b) {
const sentinel = new ListNode(0);
let tail = sentinel;
while (a !== null && b !== null) {
if (a.val <= b.val) { tail.next = a; a = a.next; }
else { tail.next = b; b = b.next; }
tail = tail.next;
}
tail.next = a !== null ? a : b;
return sentinel.next;
}
function mergeKLists(lists) {
if (lists.length === 0) return null;
let round = lists.slice();
while (round.length > 1) {
const next = [];
for (let i = 0; i < round.length; i += 2) {
next.push(i + 1 < round.length ? mergeTwo(round[i], round[i + 1]) : round[i]);
}
round = next;
}
return round[0];
}Complexity side by side
| Approach | Time | Extra memory |
|---|---|---|
| Gather, sort, rebuild | O(N log N) | O(N) |
| Merge one list at a time | O(N k) worst case | O(1) |
| Min-heap of heads | O(N log k) | O(k) |
| Pairwise rounds | O(N log k) | O(1) iterative, O(log k) if written recursively |
Inputs to try
- An empty array of lists, and an array that holds only empty lists.
- One list, which should come back unchanged.
- Many equal values spread across lists, to exercise the tie-breaker.
- Lists of very different lengths, such as one long list and many single nodes.
- Negative numbers, in case your code uses zero as a sentinel value by mistake.
Mistakes that come up
- Pushing node objects into Python's heap without a tie-breaker, which fails on equal values.
- Pushing empty lists into the heap and dereferencing nothing later.
- Pushing every node at the start, which costs O(N) memory and loses the log k advantage.
- In the pairwise version, dropping the last list when k is odd.
How to explain it out loud
Fictional example
- Candidate
- The next output node is always one of the current heads, so I need the minimum of k things over and over. A min-heap does that in log k.
- Candidate
- Each node goes in and out once, so it is N log k time and k extra memory. In Python I add the list index to each heap entry so equal values never compare nodes.
- Candidate
- If a heap is not handy, I can merge pairs of lists in rounds. Same N log k bound, and it reuses the two-list merge from merge sort.
Where to go next
Reverse Nodes in k-Group is a different kind of hard list problem, all about rewiring in place. Copy List with Random Pointer adds a second pointer per node. The pairwise rounds here are divide and conquer, the same recursive split that drives Maximum Depth of Binary Tree.
Natively in your practice sessions
This problem rewards being able to argue between two good answers. During practice, Natively on Mac or Windows can capture the problem from a screenshot and suggest the heap or pairwise approach with its complexity, which is a quick check on your own reasoning. Rehearse the explanation out loud and its transcript shows whether you mentioned the tie-breaker and the O(N log k) bound. Learn about the AI interview assistant.
Questions people ask
What is the best way to merge k sorted lists?
Use a min-heap holding the head of each list: pop the smallest, append it, push its successor. With N nodes in total, that is O(N log k) time and O(k) extra memory.
Can you merge k sorted lists without a heap?
Yes. Merge the lists in pairs, round after round, until one remains. There are about log k rounds and each touches every node once, so it is also O(N log k).
Why does Python's heapq fail with list nodes?
When two values tie, Python compares the next tuple element, and nodes cannot be compared. Add a unique tie-breaker such as the list index before the node.
What is the complexity of merging the lists one by one?
About O(N k) in the worst case, because the nodes merged early get walked again in every later merge.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
