Data Structures & AlgorithmsVery hardProduct Company SDE · heap round

Problem: Find the 3 smallest pair sums from A = [1, 7, 11] and B = [2, 4, 6], using a heap that starts with each A element paired with B[0]. What is printed?

Problem: Find the 3 smallest pair sums from A = [1, 7, 11] and B = [2, 4, 6], using a heap that starts with each A element paired with B[0]. What is printed?
import heapq
a = [1, 7, 11]
b = [2, 4, 6]
k = 3
h = [(a[i] + b[0], i, 0) for i in range(min(len(a), k))]
heapq.heapify(h)
res = []
for _ in range(k):
    s, i, j = heapq.heappop(h)
    res.append((a[i], b[j]))
    if j + 1 < len(b):
        heapq.heappush(h, (a[i] + b[j + 1], i, j + 1))
print(res)
What is printed?
  1. A. [(1, 2), (7, 2), (1, 4)]
  2. B. [(1, 2), (1, 4), (1, 6)]
  3. C. [(1, 2), (1, 4), (7, 2)]
  4. D. [(1, 2), (11, 2), (1, 4)]

Correct answer: B. [(1, 2), (1, 4), (1, 6)]

The heap always pops the smallest current sum, and extending the pair (1, 2) to (1, 4) and (1, 6) gives the first three sums 3, 5 and 7. The pair (7, 2) with sum 9 comes later.

More Coding Interview Problems questions

Exams that ask this topic