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?- A. [0, 1, 2, 4, 4, 9, 10]
- B. [0, 1, 2, 4, 9, 10]
- C. [1, 4, 9, 2, 4, 0, 10]
- 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
- Problem: Maintain the median of a stream with two heaps (max-heap for the lower half, min-heap for the upper half). python import heapq…
- Problem: Connect ropes into one; joining two ropes costs the sum of their lengths. Find the minimum total cost. python import heapq def…
- Problem: Return the k points closest to the origin (ties broken by smaller index). python import heapq pts = [(3, 3), (5, -1), (-2, 4)…
- Problem: Tasks labelled by letters each take 1 unit; the same task needs n idle units between repeats. Find the least total time. python…
- Problem: Merge overlapping booking intervals. python def merge(iv): iv.sort(); out = [] for s, e in iv: if out and s <= out[-1][1]…
- Problem: Remove the fewest meetings so that the rest do not overlap (meetings that only touch at an endpoint are fine). python def…