Find K Pairs with Smallest Sums
Return up to k index pairs with the smallest sums from two sorted arrays.
Open on LeetCode ↗Intuition
Generating and sorting every pair costs O(mn log(mn)), even when k is small. For a fixed index in nums1, pairing it with successive elements of sorted nums2 creates a sorted row of sums. The task is therefore to merge several sorted rows. A min-heap exposes the smallest current head and advances only the row that supplied it.
Combining elements from sorted inputs often forms a monotone grid or sorted rows. If only the first k combinations are required, use best-first heap expansion instead of materializing the entire Cartesian product.
Approach
Seed only useful sorted rows
For each of the first min(k, len(nums1)) values, push its pair with nums2[0]. No later row can contribute before k earlier or equal row heads because nums1 is sorted.
Pop the globally smallest row head
The heap stores (sum, i, j). Remove its minimum, append [nums1[i], nums2[j]], and count it toward the requested output.
Advance within the selected row
If j + 1 exists, push (nums1[i] + nums2[j + 1], i, j + 1). Repeat until k pairs are returned or the heap empties because all possible pairs were used.
Solution
Common pitfalls
Seeding every possible pair
for i in range(len(nums1)):
for j in range(len(nums2)):
heappush(heap, (...))for i in range(min(k, len(nums1))):
heappush(heap, (nums1[i] + nums2[0], i, 0))Materializing the Cartesian product defeats the output-sensitive advantage.
Advancing both indices
heappush(heap, (..., i + 1, j + 1))
heappush(heap, (..., i, j + 1))
Each heap entry belongs to one fixed nums1 row, whose next sum advances only in nums2.
Assuming k pairs always exist
while len(result) < k:
while heap and len(result) < k:
The Cartesian product may contain fewer than k pairs.
Edge cases
Return an empty list before reading the first element of nums2.
The loop ends when the heap becomes empty and returns every available pair.
Index-based heap entries preserve each distinct pair occurrence.