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 smallest value overall is 1, the first value of the second row. After it the rows start with 2, 4 and 3, so 2 is next, and so on. The third row runs out after 5, which leaves 6, 9 and 10 at the end.

lock icon+14 hidden tests on Submit

challenge icon

Follow-up

Find the smallest range [a, b] that holds at least one value from every row. Can the same heap of row heads, plus the largest head so far, find it in O(N log k)?

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

Case 1

Case 2

Case 3

Input

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

Expected

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