AlgoFrames

Merge k sorted lists

Standard · Write code · about 15 min

lists holds k lists, and each one is sorted from smallest to largest. Merge them into one sorted list and return it.

Aim for O(n log k) time, where n is the total number of values: keep only the front value of each list in a min-heap.

Example 1

Input:

[[[1,4],[2,5],[3]]]

Output:

[1,2,3,4,5]

The heap starts with 1, 2 and 3, one front value per list.

Example 2

Input:

[[[],[0,0,9],[-2]]]

Output:

[-2,0,0,9]

Empty lists add nothing.

Constraints

  • 0 ≤ k ≤ 500 lists
  • 0 ≤ lists[i].length ≤ 500
  • Each list is sorted in increasing order
  • -10,000 ≤ lists[i][j] ≤ 10,000

Learn the idea first: Priority queues in practice: top-k, k-way merge, scheduling, a visual lesson.

More Priority queues in practice: top-k, k-way merge, scheduling problems