Lowest-Sum Pairs Across Two Sorted Lists
Heaps, Sorting & SearchAuto-graded · 22 test casesLast updated
Select the k cheapest cross-array pairs from two sorted lists using a heap-based k-way merge, with a deterministic ordering for ties.
You are given two integer lists, first and second, each sorted in non-decreasing order, and a positive integer k.
A pair is a two-element list [a, b] where a is taken from first and b is taken from second. Two pairs are considered different if they use different positions, even when their values are equal. Pairs that use different positions but have equal values therefore each count separately.
Return the k pairs with the smallest sums a + b, as a list of [a, b] lists, in the following order:
- Ascending by sum
a + b. - If sums are equal, ascending by
a. - If both the sum and
aare equal, ascending byb. This also meansbis determined by the earlier rules, so such pairs are identical in value.
If fewer than k pairs exist in total (that is, len(first) * len(second) < k), return every possible pair in the order above.
Constraints
1 <= len(first), len(second) <= 10^5-10^9 <= first[i], second[j] <= 10^91 <= k <= 10^4- Both lists are sorted in non-decreasing order.
- The total number of pairs can reach
10^10, so generating every pair is not feasible.
Examples
Example 1
Input: smallest_sum_pairs([1, 7, 11], [2, 4, 6], 3)
Output: [[1, 2], [1, 4], [1, 6]]
Example 2
Input: smallest_sum_pairs([1, 1, 2], [1, 2, 3], 2)
Output: [[1, 1], [1, 1]]
Example 3
Input: smallest_sum_pairs([1, 2], [3, 4], 10)
Output: [[1, 3], [1, 4], [2, 3], [2, 4]]
Example 4
Input: smallest_sum_pairs([-1, 0, 2], [-3, 1, 4], 4)
Output: [[-1, -3], [0, -3], [2, -3], [-1, 1]]
Hints
Hint 1
Think of all pairs as a grid: for a fixed element of the first list, its sums with the second list never decrease as you move along the second list. Each row is already sorted.
Hint 2
You are effectively merging several sorted rows and keeping only the first k results. A min-heap holding one candidate per row is the standard tool.
Hint 3
Only the first min(k, len(first)) rows can ever matter. Seed the heap with each such row's first pair, and after popping a pair, push the next pair in the same row. Use a heap key of (sum, a, b, row, col) so ties come out in the required order.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Lay out every pair in a grid where row i holds the pairs (first[i], second[0]), (first[i], second[1]), and so on. Because second is sorted, the sums along each row never decrease. The task becomes: merge several sorted rows and take the first k items. That is a classic k-way merge using a min-heap.
- Seed the heap with the first pair of each of the first
min(k, len(first))rows. Each heap entry is the tuple(sum, a, b, i, j). - Pop the smallest entry and append
[a, b]to the answer. - If the popped entry sits at column
jin rowiand columnj + 1exists, push the entry for(i, j + 1). - Stop when
kpairs have been collected or the heap is empty (which happens whenkexceeds the number of available pairs).
Python compares tuples left to right, so equal sums are ordered by a, then b, then by indices. This gives exactly the required output order.
Why it works
- The popped item is always the global minimum of what remains. Any unpopped pair
(i, j)has a frontier entry(i, j')withj' <= jin the heap. Its sum is no larger,ais the same, andbis no larger, so the frontier key is<=the key of(i, j). The heap minimum is therefore at most every remaining pair. - Only the first
min(k, len(first))rows are needed. For any pair in a rowi >= k, thekpairs(first[i'], second[0])withi' < kall come before it under the full ordering: their sums are no larger, ties on sum are broken by a smaller-or-equala, and remaining ties by the smaller row index. So that pair can never be in the topk. - No duplicates are pushed. Every pair has exactly one predecessor in its row, so no visited set is required.
- Negative values and duplicates need no special handling, since only relative order matters and each position is tracked separately.
Complexity
Let L = min(k, len(first)).
- Time:
O(L + k log L)(heapify the seeds, then at mostkpops andkpushes on a heap of size at mostL). - Space:
O(L)for the heap plusO(k)for the output.
Reference solution
import heapq
from typing import List
def smallest_sum_pairs(first: List[int], second: List[int], k: int) -> List[List[int]]:
if not first or not second or k <= 0:
return []
rows = min(k, len(first))
heap = []
# One starting candidate per relevant row: the pair with second[0].
for i in range(rows):
heap.append((first[i] + second[0], first[i], second[0], i, 0))
heapq.heapify(heap)
result = []
while heap and len(result) < k:
_, a, b, i, j = heapq.heappop(heap)
result.append([a, b])
nj = j + 1
if nj < len(second):
heapq.heappush(heap, (first[i] + second[nj], first[i], second[nj], i, nj))
return result