Menu
CoddyTech

Merge k Sorted Lists

You get k lists of integers as the rows of lists. Each row is sorted in non-decreasing order, rows can have different lengths, and no row is empty.

Merge them into one list that holds every value from every row, sorted in non-decreasing order, and return it. A value that appears several times, in one row or in several, appears that many times in the result.

Function

mergeKLists(lists: integer-2d-array) → integer-array
listsinteger-2d-array
the sorted lists, one per row, of possibly different lengths
Returnsinteger-array
every value from every row, in one sorted list

Constraints

  • 1 ≤ lists.length ≤ 104
  • 1 ≤ lists[i].length, and all rows together hold at most 104 values
  • -104 ≤ lists[i][j] ≤ 104
  • Every row is sorted in non-decreasing order.

Examples

Input
lists = [[2, 6, 9], [1, 4, 10], [3, 5]]
Output
[1, 2, 3, 4, 5, 6, 9, 10]
Explanation
The rows start with 2, 1 and 3, so 1 comes first. The heads are then 2, 4 and 3, so 2 follows, and so on. The third row runs out after 5, leaving 6, 9 and 10.
challenge icon

Follow-up

Find the smallest range [a, b] holding a value from every row. Can a heap of row heads plus the largest head do it in O(N log k)?

Reset code
def mergeKLists(lists):
    # Write code here

Test #1

Test #2

Test #3

Argument

lists = [[2, 6, 9], [1, 4, 10], [3, 5]]

Expected Output

[1, 2, 3, 4, 5, 6, 9, 10]