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?- A. [(1, 2), (7, 2), (1, 4)]
- B. [(1, 2), (1, 4), (1, 6)]
- C. [(1, 2), (1, 4), (7, 2)]
- 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
- Problem: An undirected connected graph has an Euler circuit (a closed walk using every edge exactly once) if and only if which condition…
- Problem: Using 2D prefix sums on M = [[1,2,3],[4,5,6],[7,8,9]], what is the sum of the rectangle with rows 1..2 and columns 1..2…
- Problem: How many pairs (i < j) of a = [1, 2, 3, 4, 5, 6, 7] have a[i] + a[j] divisible by 4? python a = [1, 2, 3, 4, 5, 6, 7] print(sum(1…
- Problem: Count the subarrays of a = [10, 5, 2, 6] whose product is strictly less than k = 100. python def cnt(a, k): if k <= 1: return 0 p…
- Problem: How many distinct subsequences (including the empty one) does 'aba' have? Run the DP below. python def dsub(s): dp = [1] last =…
- Problem: The minimum number of insertions to make 'abcab' a palindrome equals n minus the length of its longest palindromic subsequence…