Merge K Sorted Lists (LeetCode 23): Solution and Explanation

Hard
Linked List
Divide And Conquer
Heap
Merge Sort

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.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

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)

  1. If lists is empty, return None.
  2. While more than one list remains, create an empty mergedLists for the next round.
  3. Step through lists two at a time. Take l1 = lists[i] and l2 = lists[i + 1], or None if there is no partner.
  4. Merge each pair with mergeTwoLists and append the result to mergedLists. A lone list merges with None and passes through unchanged.
  5. Replace lists with mergedLists and repeat. When one list remains, return lists[0].
  6. mergeTwoLists uses 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]]
  1. Round one pairs list 0 with list 1. Merging [1,4,5] and [1,3,4] gives [1,1,3,4,4,5].
  2. List 2, [2,6], has no partner, so it is merged with None and stays [2,6].
  3. lists becomes [[1,1,3,4,4,5],[2,6]].
  4. Round two merges those two lists into [1,1,2,3,4,4,5,6].
  5. 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.next

Time and space complexity

Time

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.

Space

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, and lists[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.