Merge k Sorted Lists
Hard
Topics
You are given an array of k sorted linked lists. Merge them into one sorted list and return its head.
Example 1
list 1
list 2
list 3
merged
Each of the 3 input lists is already sorted, and the result must be one sorted list holding all of their nodes. The lists may differ wildly in length, and an empty one is allowed.
Linked list values from head to tail.
Input: lists = [[1,4,5],[1,3,4],[2,6]] Output: [1,1,2,3,4,4,5,6]
Example 2
no lists
Input: lists = [] Output: []
Constraints
- 0 <= k <= 10^4
- 0 <= list length <= 500
- Each list is sorted non-decreasing.
Editorial — intuition, approach, complexity and pitfalls
Intuition
The frontier of the merged list is always the smallest current head across the k lists. A min-heap of the k heads gives that smallest element in O(log k); alternatively pair up lists and merge two at a time (divide and conquer).
Approach
- Push the head of every non-empty list into a min-heap keyed by value.
- Pop the smallest, append it to the result, and push its next node.
- Repeat until the heap empties.
Dry Run
lists = [1,4,5], [1,3,4], [2,6]
heap entries are (value, list index, node). Shown as (value, list index).
seed heap=[(1,0) (1,1) (2,2)] one head per list
pop (1,0) -> 1 push (4,0) heap=[(1,1) (2,2) (4,0)]
pop (1,1) -> 1 push (3,1) heap=[(2,2) (4,0) (3,1)]
pop (2,2) -> 2 push (6,2) heap=[(3,1) (4,0) (6,2)]
pop (3,1) -> 3 push (4,1) heap=[(4,0) (6,2) (4,1)]
pop (4,0) -> 4 push (5,0) heap=[(4,1) (6,2) (5,0)]
pop (4,1) -> 4 list spent heap=[(5,0) (6,2)]
pop (5,0) -> 5 list spent heap=[(6,2)]
pop (6,2) -> 6 heap=[]
answer 1 1 2 3 4 4 5 6
Two things the trace makes visible. The heap never holds more than 3 entries --
one per list, never one per node -- which is why space is O(k) and not O(n).
And look at the two (1, ...) entries: the list index is a TIEBREAKER, not
decoration. Without it Python would fall through to comparing the third tuple
element, and ListNode has no ordering, so equal values would raise TypeError.Complexity
- Time — O(N log k): each of the N total nodes is pushed/popped once from a heap of size k.
- Space — O(k): the heap holds at most one node per list.
Common Pitfalls
- Include a tiebreaker (list index) in the heap key so nodes with equal values never get compared directly.
Full Solution — all languages
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def mergeKLists(self, lists):
import heapq
heap=[]
for i,node in enumerate(lists):
if node: heapq.heappush(heap,(node.val,i,node))
dummy=ListNode(); tail=dummy
while heap:
val,i,node=heapq.heappop(heap)
tail.next=node; tail=node
if node.next: heapq.heappush(heap,(node.next.val,i,node.next))
return dummy.nextimport java.util.*;
class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
}
}
class Solution {
public ListNode mergeKLists(ListNode[] lists) {
PriorityQueue<ListNode> pq=new PriorityQueue<>((a,b)->a.val-b.val);
// min-heap of k heads: O(N log k)
for(ListNode node:lists) if(node!=null) pq.offer(node);
ListNode dummy=new ListNode(0),tail=dummy;
while(!pq.isEmpty()) {
ListNode node=pq.poll();
tail.next=node;
tail=node;
if(node.next!=null) pq.offer(node.next);
}
return dummy.next;
}
}#include <bits/stdc++.h>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x): val(x), next(nullptr) {
}
};
class Solution {
public: ListNode* mergeKLists(vector<ListNode*>& lists) {
auto cmp=[](ListNode* a,ListNode* b) {
return a->val>b->val;
};
// min-heap of k heads: O(N log k)
priority_queue<ListNode*,vector<ListNode*>,decltype(cmp)> pq(cmp);
for(ListNode* node:lists) if(node) pq.push(node);
ListNode dummy(0);
ListNode* tail=&dummy;
while(!pq.empty()) {
ListNode* node=pq.top();
pq.pop();
tail->next=node;
tail=node;
if(node->next) pq.push(node->next);
}
return dummy.next;
}
};/** Node shape: { val, next }. Build/return plain objects or use this ctor. */ function ListNode(val, next) {
this.val = (val === undefined ? 0 : val);
this.next = (next === undefined ? null : next);
}
/**
* @param {ListNode[]} lists
* @return {ListNode}
*/ var mergeKLists = function(lists) {
if(!lists||lists.length===0) return null;
const mergeTwo=(a,b)=> {
const d=new ListNode(0);
let t=d;
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||b;
return d.next;
};
const N=lists.length;
for(let interval=1;interval<N;interval*=2) {
// pairwise merge: O(N log k)
for(let i=0;i+interval<N;i+=interval*2) lists[i]=mergeTwo(lists[i],lists[i+interval]);
}
return lists[0];
};