Python coding

Merge many sorted lists

You get lists, a list of k lists of integers, each sorted in non-decreasing order (some may be empty). Return one sorted list with every value from all of them, duplicates included.

Aim for O(N log k) for N values in total, instead of concatenating and sorting.

Besides the tests, one large input (1,800 lists, 5,400 values) with a ~250 ms limit (scaled to your device's speed): brute force won't pass.

  • merge_sorted([[1,4,5],[1,3,4],[2,6]]) → [1,1,2,3,4,4,5,6]
  • merge_sorted([]) → []
  • merge_sorted([[],[1]]) → [1]
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

The next output value is always the smallest of the current heads. A min-heap of heads gives it in O(log k).

Hint 2

Push (value, i, j) for list i, position j. Each pop tells you which list to advance: push its next value, if any.

Solution and why it works
pythonO(N log k), N = total values · O(k) besides the output
import heapq


def merge_sorted(lists: list[list[int]]) -> list[int]:
    heap = [(lst[0], i, 0) for i, lst in enumerate(lists) if lst]
    heapq.heapify(heap)
    out = []
    while heap:
        value, i, j = heapq.heappop(heap)
        out.append(value)
        if j + 1 < len(lists[i]):
            heapq.heappush(heap, (lists[i][j + 1], i, j + 1))
    return out

The heap holds at most one entry per list, the smallest unused value of each, so its root is the global minimum. Each of the N values is pushed and popped once at O(log k): O(N log k) with O(k) extra memory. The list index in the tuple says whose successor to push. Skip empty lists when seeding the heap, or lst[0] fails.