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?- A. [(1, 2), (1, 3), (3, 2), (3, 3)]
- B. [(1, 2), (1, 3), (1, 8), (3, 2)]
- C. [(1, 2), (3, 2), (1, 3), (9, 2)]
- 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
- Problem: Median of two sorted arrays in O(log(min(m, n))) by binary searching the partition of the shorter array. python def median(a, b)…
- Problem: Find the k-th positive integer missing from a strictly increasing array, by binary search on 'missing before index i' = a[i] − (i…
- Problem: Find the area of the largest square of 1s in a binary matrix. python def square(m): R, C = len(m), len(m[0]); dp = [[0] (C + 1)…
- Problem: Length of the longest common CONTIGUOUS subarray of two arrays (DP on suffix matches). python def common(a, b): dp = [[0] (len(b)…
- Problem: A knight makes k uniformly random moves (8 directions) on an n × n board; once it leaves the board it stays off. What is the…
- Problem: Choose the largest number of binary strings using at most m zeros and n ones in total (2-D 0/1 knapsack). python def most(strs…