Find K Pairs with Smallest Sums
Find K Pairs with Smallest Sums is LeetCode 373 (Medium). You get two integer arrays nums1 and nums2, both sorted in non-decreasing order, and an integer k.
- A pair
(u, v)takes one elementufromnums1and one elementvfromnums2. Its value is the sumu + v. - Return the
kpairs with the smallest sums. - Pairs are told apart by position, so equal values at different indices make different pairs.
Each array can hold 10⁵ elements, so there can be 10¹⁰ pairs: far too many to list. k is at most 10⁴ and never more than the number of pairs.
- 1 <= nums1.length, nums2.length <= 10⁵
- -10⁹ <= nums1[i], nums2[i] <= 10⁹
- nums1 and nums2 both are sorted in non-decreasing order.
- 1 <= k <= 10⁴
- k <= nums1.length * nums2.length
Intuition
Picture the pairs as a grid: row i belongs to nums1[i], column j belongs to nums2[j], and each cell holds their sum. Both arrays are sorted, so every row grows from left to right.
So the smallest pair a row has not handed out yet is always its leftmost untaken cell. At any moment there is only one real candidate per row, and the next answer is the smallest of those candidates.
A min-heap keeps the smallest candidate on top. Put each row's first cell in the heap, then repeat: pop the top, record its pair, and push the cell to its right. Each row acts as a sorted list that is never stored, and the heap merges them.
Two sorted inputs, a way of combining them that keeps the order, and only the first k results wanted: that is best-first search over a sorted grid. The same heap of frontier cells solves Kth Smallest Element in a Sorted Matrix (378), Merge k Sorted Lists (23) and Ugly Number II (264).
Approach
Before reading on, draw the 3 × 3 sum grid for two small sorted arrays. Mark the cell you would take first. Once it is taken, which cells could be second? Aim for O(k log k) time.
Seed one cell per row
Push (nums1[i] + nums2[0], i, 0) for each i < min(k, len(nums1)), because column 0 holds each row's smallest sum. Rows from index k on can be left out: the k rows above each start with a sum no larger, so they already supply k pairs that are at least as small.
Pop the smallest and record it
heappop returns the smallest (sum, i, j). Append [nums1[i], nums2[j]] to the result. The entry carries the indices as well as the sum, so the code knows both which pair it took and which cell comes next.
Push the cell to its right
If j + 1 < len(nums2), push (nums1[i] + nums2[j + 1], i, j + 1). A row only ever moves right, so the heap holds at most one cell per row and no cell goes in twice. A row with no columns left simply drops out of the heap.
Stop after k pairs
Loop while the result has fewer than k pairs and the heap is not empty. LeetCode promises k <= n·m, so the heap never runs dry first, but the extra check costs nothing and protects you if that promise is dropped.
Why each pop is the next smallest pair
For every seeded row, the heap holds that row's leftmost untaken cell, and every other untaken cell in the row lies to its right, so it is no smaller. The heap top is therefore no larger than any pair not yet taken. Popping it and pushing its right neighbour keeps this true.
Code in Python, C++ and Java
Common pitfalls
Building every pair, then sorting
pairs = sorted(
([u, v] for u in nums1 for v in nums2), key=sum
)
return pairs[:k]heap = [(nums1[i] + nums2[0], i, 0) for i in range(min(k, len(nums1)))] # pop k times, pushing (i, j + 1) each time
With 10⁵ elements on each side that is 10¹⁰ pairs: out of memory long before the sort finishes. The heap version only ever touches about 2k cells.
Pushing both the right and the lower neighbour
heappush(heap, (nums1[i] + nums2[j + 1], i, j + 1)) heappush(heap, (nums1[i + 1] + nums2[j], i + 1, j))
# seed every row's column 0 up front, # then push only the right neighbour heappush(heap, (nums1[i] + nums2[j + 1], i, j + 1))
Starting from (0, 0) and expanding in both directions reaches (1, 1) from both (0, 1) and (1, 0), so it is pushed and output twice. That version needs a visited set; seeding the rows and only moving right needs none.
Comparing sums with 32-bit subtraction
new PriorityQueue<int[]>((a, b) ->
(nums1[a[0]] + nums2[a[1]]) - (nums1[b[0]] + nums2[b[1]]))int sa = nums1[a[0]] + nums2[a[1]]; int sb = nums1[b[0]] + nums2[b[1]]; return Integer.compare(sa, sb);
Each sum fits in an int, but the difference of two sums may not. With nums1 = nums2 = [-10⁹, 10⁹], the sums 2·10⁹ and −2·10⁹ differ by 4·10⁹, which wraps to a negative number, so the comparator returns the wrong sign and the heap order silently breaks. Integer.compare never subtracts.
Edge cases
Heap entries carry indices, not values, so nums1 = [1, 1] gives two different rows and both [1, x] pairs are returned. Never deduplicate by value.
Every pair is returned. Rows leave the heap one by one as they run out of columns, and the heap is empty exactly when the last pair is popped.
min(k, len(nums1)) seeds every row; the loop then walks right along the rows until k pairs are out.
Complexity
min(k, n) entries. Seeding is O(min(k, n)) and each of the k pops and at most k pushes costs O(log min(k, n)). The returned list itself is O(k).Find K Pairs with Smallest Sums FAQ
Why does each heap entry store the sum and the indices?
The sum decides the order; the indices say which pair to output and which cell to push next. In Python, heapq compares tuples item by item, so (sum, i, j) sorts by sum and breaks ties by row with no custom comparator.
Can this be solved with binary search instead of a heap?
Yes. Binary search on a sum value s: count the pairs with sum ≤ s using two pointers in O(n + m), and find the smallest s whose count reaches k. Then collect every pair below s and top up with pairs equal to s. It runs in O((n + m) log(range)) plus the output, which only beats the heap when k is large next to n + m.