Merge K Sorted Lists (LeetCode 23): Solution and Explanation
You are given an array of k linked lists, each sorted in ascending order. Combine them all into a single sorted linked list and return its head, reusing the existing nodes.
Watch it run step by step
Try your own input and write the code →Intuition
A straightforward idea is to merge the lists one after another: merge the first two, then merge the result with the third, and so on. That reuses the familiar two-list merge, but the growing result list is re-scanned in every step. With N total nodes spread evenly, the early nodes get touched about k times, which gives O(N × k) time.
The waste comes from the lopsided order of merges. Merge sort faces the same issue and solves it by always merging pieces of similar size. Apply that here: in one round, merge lists 0 and 1, lists 2 and 3, and so on. Every node moves exactly once per round, so a round costs O(N), and the number of lists halves each time.
After about log k rounds only one list remains, giving O(N log k) total. The nice part is that the only merging primitive is the classic two-list merge with a dummy head, so the code stays simple. A min-heap holding the current head of each list reaches the same bound with a different structure, and either answer is fine in an interview as long as you can explain why it beats sequential merging.
Approach: Pairwise merging in rounds (divide and conquer)
- If
listsis empty, return None. - While more than one list remains, create an empty
mergedListsfor the next round. - Step through
liststwo at a time. Takel1 = lists[i]andl2 = lists[i + 1], or None if there is no partner. - Merge each pair with
mergeTwoListsand append the result tomergedLists. A lone list merges with None and passes through unchanged. - Replace
listswithmergedListsand repeat. When one list remains, returnlists[0]. mergeTwoListsuses a dummy head and a tail pointer, always attaching the smaller front node and splicing on whatever is left at the end.
Step-by-step example
lists = [[1,4,5],[1,3,4],[2,6]]
- Round one pairs list 0 with list 1. Merging [1,4,5] and [1,3,4] gives [1,1,3,4,4,5].
- List 2, [2,6], has no partner, so it is merged with None and stays [2,6].
listsbecomes [[1,1,3,4,4,5],[2,6]].- Round two merges those two lists into [1,1,2,3,4,4,5,6].
- Only one list remains, so the loop ends and the function returns [1,1,2,3,4,4,5,6].
Code: Python, Java, C++
1class Solution:
2 def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]:
3 if not lists or len(lists) == 0:
4 return None
5
6 while len(lists) > 1:
7 mergedLists = []
8
9 for i in range(0, len(lists), 2):
10 l1 = lists[i]
11 l2 = lists[i + 1] if (i + 1) < len(lists) else None
12 mergedLists.append(self.mergeTwoLists(l1, l2))
13 lists = mergedLists
14
15 return lists[0]
16
17 def mergeTwoLists(self, l1, l2):
18 dummy = ListNode()
19 tail = dummy
20 while l1 and l2:
21 if l1.val < l2.val:
22 tail.next = l1
23 l1 = l1.next
24 else:
25 tail.next = l2
26 l2 = l2.next
27 tail = tail.next
28 if l1: tail.next = l1
29 if l2: tail.next = l2
30 return dummy.next1class Solution {
2 public ListNode mergeKLists(ListNode[] lists) {
3 if (lists == null || lists.length == 0) return null;
4
5 PriorityQueue<ListNode> pq = new PriorityQueue<>((a,b) -> a.val - b.val);
6 for (ListNode list : lists) {
7 if (list != null) pq.add(list);
8 }
9
10 ListNode dummy = new ListNode();
11 ListNode tail = dummy;
12
13 while (!pq.isEmpty()) {
14 ListNode node = pq.poll();
15 tail.next = node;
16 tail = tail.next;
17
18 if (node.next != null) pq.add(node.next);
19 }
20
21 return dummy.next;
22 }
23}1class Solution {
2public:
3 ListNode* mergeKLists(vector<ListNode*>& lists) {
4 if (lists.empty()) return nullptr;
5
6 auto cmp = [](ListNode* a, ListNode* b) { return a->val > b->val; };
7 priority_queue<ListNode*, vector<ListNode*>, decltype(cmp)> pq(cmp);
8
9 for (auto l : lists) {
10 if (l) pq.push(l);
11 }
12
13 ListNode dummy;
14 ListNode* tail = &dummy;
15
16 while (!pq.empty()) {
17 ListNode* node = pq.top();
18 pq.pop();
19
20 tail->next = node;
21 tail = tail->next;
22
23 if (node->next) pq.push(node->next);
24 }
25
26 return dummy.next;
27 }
28};Time and space complexity
O(N log k)
N is the total number of nodes. Each round moves every node once through a two-list merge, costing O(N), and the number of lists halves each round, so there are about log k rounds.
O(k)
The merges themselves relink nodes in place. The extra memory is the mergedLists array, which holds up to k / 2 head pointers per round.
Other approaches
Min-heap of list heads (time O(N log k), space O(k))
Push the head of each non-empty list into a min-heap keyed by value, with a tiebreaker index. Pop the smallest node, append it to the result, and push its successor. The heap never holds more than k nodes.
Sequential merging (time O(N × k), space O(1))
Merge lists into a running result one at a time. It is the simplest to write but repeatedly re-scans the growing result, which is slow when k is large.
Common mistakes
- Reading
lists[i + 1]without checking bounds when the number of lists is odd. - Merging sequentially and calling it O(N log k). Only balanced pairing or a heap achieves that bound.
- In the heap version, pushing raw nodes in Python. Nodes are not comparable, so equal values crash unless you add an index tiebreaker.
- Skipping the empty-input check. With
lists = []the while loop never runs, andlists[0]raises an index error.
Frequently asked questions
What is the time complexity of merging k sorted lists?
Both divide and conquer and the min-heap approach run in O(N log k), where N is the total number of nodes. Merging lists one by one is O(N × k).
Heap or divide and conquer for Merge K Sorted Lists?
They share the same time bound. Divide and conquer reuses the two-list merge and needs no heap, while the heap version processes nodes in a single stream and adapts well when lists arrive over time.
Why is sequential merging slower?
Each new merge re-walks the entire accumulated result. The first list's nodes get scanned in almost every merge, which adds up to roughly k passes over the data instead of log k.