Skip to content
Problem 23 · LeetCode 23(opens in a new tab)

Merge k Sorted Lists

HardDivide and conquer

You are given lists, an array of k linked lists. Each list is already sorted from smallest to largest value.

Combine all of their nodes into one linked list that is also sorted from smallest to largest, and return its head. If there are no nodes at all, return an empty list.

Example 1

Input:  lists = [[2, 6, 8], [1, 5], [3, 4, 9]]
Output: [1, 2, 3, 4, 5, 6, 8, 9]
Why:    all eight nodes, in order
2 more examples and the constraints

Example 2

Input:  lists = []
Output: []
Why:    no lists means no nodes

Example 3

Input:  lists = [[], [7]]
Output: [7]
Why:    the empty list adds nothing

Constraints

  • 0 ≤ k ≤ 10,000
  • Each list has 0 to 500 nodes, and all lists together have at most 10,000
  • Every value is between −10,000 and 10,000
  • Each list is sorted in ascending order

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Merge one list at a timeO(k·N)
  2. Divide and conquerO(N log k)
  3. Min-heap of headsO(N log k)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for 10,000 lists of one nodeVerdict
Merge one list at a timeO(k·N)
Correct, too slow for many lists
Divide and conquerO(N log k)
Passes; no extra space
Min-heap of headsO(N log k)
Best; the classic answer

k = number of lists, N = total number of nodes.

Edge cases to test

  • No lists at all. [] must return an empty list, not crash on lists[0].
  • Empty lists inside. [[], [7]] or [[]]: never push a null head into the heap.
  • Equal values. Several heads with the same value; in Python the tie must not compare two nodes.
  • One list. [[-3, 0, 5]] is already the answer.

Common mistakes

  • Pushing null heads of empty lists into the heap.
  • In Python, pushing (val, node) so that a tie on val tries to compare two ListNode objects and fails.
  • Copying values into new nodes and sorting them: it works, but misses the point that each list is already sorted.

How to talk through it

  1. 1Clarify. Can lists be empty, or can there be no lists? Should I reuse the nodes or build new ones?
  2. 2Give the simple answer. Merge the lists one at a time; say why that is O(k·N) because the result is walked again and again.
  3. 3Name the key fact. The next node of the answer is always one of the k heads. A min-heap gives me the smallest head in O(log k).
  4. 4Code the heap loop. Pop, link after the tail, push the next node of the same list. Mention divide and conquer as the no-heap option.
  5. 5Test out loud. Run an empty input, a list of empty lists, and equal values before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?