Problem
Merge k sorted linked lists into one sorted list and return its head.
Original: LeetCode 23: Merge k Sorted Lists.
Examples
Example 1
`lists = [[1, 4, 5], [1, 3, 4], [2, 6]]``[1, 1, 2, 3, 4, 4, 5, 6]`Example 2
`lists = []``[]`Example 3
`lists = [[]]``[]`Constraints
k == lists.length0 <= k <= 10^40 <= lists[i].length <= 500-10^4 <= lists[i][j] <= 10^4lists[i]is sorted in ascending order.- The sum of
lists[i].lengthwill not exceed10^4.
Hints
Hint 1
Each input list is already sorted in ascending order. Some lists may be empty. The result should use the existing nodes, not copies of their values, although a value-based rebuild also passes the tests.
Hint 2
Merging many sorted sequences is a k-way merge: a min-heap of the current head of each list.
Solution
Tried it yourself? The approach, complexity, and code stay hidden until you choose.
Approach
Brute force. Collect every node, sort the values, and rebuild a list. That is O(n log n) and ignores the fact that each list is already sorted.
Optimal. A min-heap of at most k current nodes. Each pop emits one result node and may push one successor.
Alternative. Pairwise merge, or a merge-sort tree over the k lists, is also O(n log k) and needs no heap.
Complexity
- Time
- O(n log k)
O(n log k) time and O(k) extra space, where n is the total number of nodes.
- Space
- O(k)
Code
import heapq
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def merge_k_lists(lists: list[ListNode | None]) -> ListNode | None:
heap: list[tuple[int, int, ListNode]] = []
for i, node in enumerate(lists):
if node:
heapq.heappush(heap, (node.val, i, node))
dummy = tail = ListNode()
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 dummy.next
def of(*xs):
dummy = tail = ListNode()
for x in xs:
tail.next = ListNode(x)
tail = tail.next
return dummy.next
def to_list(n):
out = []
while n:
out.append(n.val)
n = n.next
return out
if __name__ == "__main__":
assert to_list(merge_k_lists([of(1, 4, 5), of(1, 3, 4), of(2, 6)])) == [1, 1, 2, 3, 4, 4, 5, 6]
assert merge_k_lists([]) is None
assert merge_k_lists([None]) is None
print("ok")import java.util.PriorityQueue;
public class MergeKSortedLists {
static class ListNode {
int val;
ListNode next;
ListNode(int val) { this.val = val; }
}
static ListNode mergeKLists(ListNode[] lists) {
var heap = new PriorityQueue<ListNode>((a, b) -> Integer.compare(a.val, b.val));
for (var node : lists) if (node != null) heap.offer(node);
var dummy = new ListNode(0);
var tail = dummy;
while (!heap.isEmpty()) {
var node = heap.poll();
tail.next = node;
tail = node;
if (node.next != null) heap.offer(node.next);
}
return dummy.next;
}
static ListNode of(int... xs) {
var dummy = new ListNode(0);
var t = dummy;
for (int x : xs) { t.next = new ListNode(x); t = t.next; }
return dummy.next;
}
static String str(ListNode n) {
var sb = new StringBuilder();
while (n != null) { sb.append(n.val).append(','); n = n.next; }
return sb.toString();
}
public static void main(String[] args) {
var merged = mergeKLists(new ListNode[] {of(1, 4, 5), of(1, 3, 4), of(2, 6)});
if (!str(merged).equals("1,1,2,3,4,4,5,6,")) throw new AssertionError(str(merged));
if (mergeKLists(new ListNode[] {}) != null) throw new AssertionError();
if (mergeKLists(new ListNode[] {null}) != null) throw new AssertionError();
System.out.println("ok");
}
}Edge cases
- Official samples: merging [1,4,5], [1,3,4] and [2,6] yields [1,1,2,3,4,4,5,6]; an empty list of lists and a list containing only a null head both yield null.
- Python's heap cannot compare ListNode objects, so the heap entry includes a unique index.
Follow-ups
- Merge Two Sorted Lists is the k = 2 special case and does not need a heap.
- If lists arrive as arrays instead of linked lists, the same heap holds (value, list index, offset).
Interview script
"This is a k-way merge. I put each list head in a min-heap, pop the smallest node into the result, and push its successor. Every node is pushed once, so the cost is n log k."
Source: LeetCode 23: Merge k Sorted Lists Source: Java SE 17 API: PriorityQueue Source: Python 3: heapq
Sources (3)
- LeetCode 23: Merge k Sorted Listsleetcode.com
- Java SE 17 API: PriorityQueuedocs.oracle.com
- Python 3: heapqdocs.python.org