Data Structures & AlgorithmsModerateProduct Company SDE · Amazon/Microsoft-style OA

Problem: Merge k sorted lists of order timestamps into one sorted list.

Problem: Merge k sorted lists of order timestamps into one sorted list.
import heapq
def merge_k(lists):
    h = [(l[0], i, 0) for i, l in enumerate(lists) if l]
    heapq.heapify(h); out = []
    while h:
        v, i, j = heapq.heappop(h); out.append(v)
        if j + 1 < len(lists[i]):
            heapq.heappush(h, (lists[i][j + 1], i, j + 1))
    return out
print(merge_k([[1, 4, 9], [], [2, 4], [0, 10]]))
What is printed?
  1. A. [0, 1, 2, 4, 4, 9, 10]
  2. B. [0, 1, 2, 4, 9, 10]
  3. C. [1, 4, 9, 2, 4, 0, 10]
  4. D. [0, 1, 2, 4, 4, 10, 9]

Correct answer: A. [0, 1, 2, 4, 4, 9, 10]

The heap holds one head per list; pop the smallest and push its successor. Including the list index i in the tuple breaks ties without comparing unorderable objects. Empty lists are skipped. O(N log k) for N total items and k lists.

More Coding Interview Problems questions

Exams that ask this topic