The pairs with the smallest sums
List the k pairs, one value from each of two sorted arrays, with the smallest sums, by treating each value of the first array as the start of a sorted list of sums. About 18 minutes.
Each value starts a sorted row
You have two sorted arrays a and b. For one value a at position i, the sums with b are a plus b at position 0, a plus b at position 1, and so on: a sorted list. So the table of all sums is made of sorted rows, one per value of a.
The smallest sum overall is the front of one of these rows, so start the heap with the first pair of each row.
first = a[0] + b[0] # the smallest sum
The heap starts with the first pair of each row: sums 3, 4 and 10. Pop 3: the pair (2, 1). Push the next in row 0: sum 7.
Take a pair, offer the next
Pop the smallest entry. It is the next pair of the answer. Then offer the next pair in the same row, the one with the next value of b, if there is one.
Stop after k pairs or when the heap is empty. Because entries are compared by sum, then by position in a, then by position in b, ties are settled the same way every time. Only the first k rows can supply the answer, so start with at most k entries.
s, i, j = heapq.heappop(heap) # the smallest sum
After popping the pair at row i and column j, which pair is pushed?
- AThe pair in the same row, with the next value of b
- BThe pair in the next row, in the same column
- CAll pairs in the row
Show the answer
The pair in the same row, with the next value of b. It is the next sum in that sorted row.
Find K pairs with the smallest sums
You are given two integer arrays a and b, both sorted in non-decreasing order, and an integer k. A pair takes one value from a and one from b. Return the k pairs with the smallest sums, listed in order of increasing sum; pairs with equal sums are listed by their position in a, then by their position in b. If there are fewer than k pairs, return all of them.
a = [1, 7, 11], b = [2, 4, 6], k = 3 → [[1, 2], [1, 4], [1, 6]]
1 ≤ length of a, b ≤ 300 · -10,000 ≤ values ≤ 10,000 · 1 ≤ k ≤ 1,000