Merge k Sorted Lists

HardLinked lists

You get an array lists of k linked lists, each sorted from smallest to largest. Merge them all into one sorted list and return its head.

On this page each list is written as an array of its values, from head to tail, so lists is an array of arrays. A list can be empty, [], and so can lists itself; the answer is then an empty list, [].

Examples

Example 1
Input:  lists = [[1, 6, 8], [2, 3, 9], [4, 5]]
Output: [1, 2, 3, 4, 5, 6, 8, 9]

Every value from the three lists, in one sorted run.

Example 2
Input:  lists = [[], [7], []]
Output: [7]

Empty lists add nothing.

Constraints

  • 0 ≤ k ≤ 10⁴
  • Each list has 0 to 500 nodes, and all of them together at most 10⁴.
  • -10⁴ ≤ node.val ≤ 10⁴
  • Each list is sorted in non-decreasing order.

Stuck?

Hint 1

At every step the next node is the smallest of the k current fronts. A min-heap hands you that one in O(log k).

Hint 2

Without a heap, merge the lists in pairs, then the results in pairs, and so on: each round halves the number of lists, so there are only log k rounds.

Still stuck? Read the solution

JavaScript
Loading the editor

Run checks your code against the 2 examples. Submit checks all 9 tests, most of them hidden.

Ctrl + Enter runs, and adding Shift submits. On a Mac, use ⌘.

blur