Data Structures & AlgorithmsHardAmazon · Microsoft OA

Problem: Return the k pairs (u from a, v from b) with the smallest sums, using a heap seeded with (a[i], b[0]).

Problem: Return the k pairs (u from a, v from b) with the smallest sums, using a heap seeded with (a[i], b[0]).
import heapq
def ksmall(a, b, k):
    h = [(a[i] + b[0], i, 0) for i in range(min(k, len(a)))]
    heapq.heapify(h); out = []
    while h and len(out) < k:
        s, i, j = heapq.heappop(h); out.append((a[i], b[j]))
        if j + 1 < len(b): heapq.heappush(h, (a[i] + b[j+1], i, j + 1))
    return out
print(ksmall([1, 3, 9], [2, 3, 8], 4))
What is printed?
  1. A. [(1, 2), (1, 3), (3, 2), (3, 3)]
  2. B. [(1, 2), (1, 3), (1, 8), (3, 2)]
  3. C. [(1, 2), (3, 2), (1, 3), (9, 2)]
  4. D. [(1, 2), (1, 3), (3, 2), (9, 2)]

Correct answer: A. [(1, 2), (1, 3), (3, 2), (3, 3)]

Sums in order: 1+2 = 3, 1+3 = 4, 3+2 = 5, 3+3 = 6, then 1+8 = 9 and 9+2 = 11. Each popped pair (i, j) pushes only (i, j + 1), so the heap never holds more than k entries.

More Coding Interview Problems questions

Exams that ask this topic