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?- A. [3, 4, 6, 7, 11, 11]
- B. [3, 4, 6, 7, 11, 12]
- C. [3, 4, 6, 7, 10, 11]
- 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
- Problem: Find all critical links (bridges) and critical routers (articulation points) with one DFS using discovery times and low-links…
- Problem: A drone must fly every route leg exactly once starting at P, choosing the alphabetically smallest destination whenever possible…
- Problem: Assign interns to projects; intern u may take only projects in adj[u], each project at most one intern. Maximum bipartite…
- Problem: For every warehouse in a tree network, compute the sum of distances to all other warehouses with two passes (rerooting)…
- Problem: Count integers in [1, N] divisible by at least one of the given numbers using inclusion–exclusion with LCMs (N up to 10⁹, so no…
- Problem: Compute C(n, r) mod a SMALL prime p = 7 when n ≥ p: Lucas' theorem versus factorials with Fermat inverses. python p = 7 fact =…