Data Structures & AlgorithmsVery hardProduct company OA

Problem: Two sorted price lists; list the 6 smallest sums a[i] + b[j] without generating all pairs (heap of frontier cells with a seen-set).

Problem: Two sorted price lists; list the 6 smallest sums a[i] + b[j] without generating all pairs (heap of frontier cells with a seen-set).
import heapq
def k_smallest_sums(a, b, k):
    h = [(a[0] + b[0], 0, 0)]; seen = {(0, 0)}; out = []
    while h and len(out) < k:
        s, i, j = heapq.heappop(h); out.append(s)
        for ni, nj in ((i + 1, j), (i, j + 1)):
            if ni < len(a) and nj < len(b) and (ni, nj) not in seen:
                seen.add((ni, nj)); heapq.heappush(h, (a[ni] + b[nj], ni, nj))
    return out
print(k_smallest_sums([1, 4, 9], [2, 3, 10], 6))
What is printed?
  1. A. [3, 4, 6, 7, 11, 11]
  2. B. [3, 4, 6, 7, 11, 12]
  3. C. [3, 4, 6, 7, 10, 11]
  4. D. [3, 4, 5, 6, 7, 11]

Correct answer: A. [3, 4, 6, 7, 11, 11]

Start from (0, 0); after popping (i, j) push (i + 1, j) and (i, j + 1). Because both lists are sorted, every unseen pair is ≥ some frontier pair, so pops come in sorted order. Sums: 1+2, 1+3, 4+2, 4+3, then 9+2 = 11 and 1+10 = 11 (both 11s are distinct pairs). The seen-set prevents (1, 1) from entering twice. O(k log k).

More Coding Interview Problems questions

Exams that ask this topic