LeetCode #373 Medium

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 element u from nums1 and one element v from nums2. Its value is the sum u + v.
  • Return the k pairs 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.

Constraints
  • 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
arrayheapbest-first-search
Open on LeetCode ↗
02

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.

How to spot this pattern

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).

03

Approach

Try it first

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.

1

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.

2

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.

3

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.

4

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.

5

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.

04

Code in Python, C++ and Java

▶1import heapq
▶2 
▶3 
▶4class Solution:
▶5 def kSmallestPairs(
▶6 self, nums1: List[int], nums2: List[int], k: int
▶7 ) -> List[List[int]]:
▶8 heap = [(nums1[i] + nums2[0], i, 0) for i in range(min(k, len(nums1)))]
▶9 heapq.heapify(heap)
▶10 result = []
▶11 while heap and len(result) < k:
▶12 _, i, j = heapq.heappop(heap)
▶13 result.append([nums1[i], nums2[j]])
▶14 if j + 1 < len(nums2):
▶15 heapq.heappush(heap, (nums1[i] + nums2[j + 1], i, j + 1))
▶16 return result
pair sumsmin-heap2461711nums2nums1357911131315173r0 c09r1 c013r2 c0resulteach row's first cell → heap
rows seeded3min(k=3, n=3)
heap(3, 0, 0) (9, 1, 0) (13, 2, 0)(sum, i, j)
grid3 × 39 pairs in all
Every row of the grid increases to the right, so each row's smallest pair is in column 0. Push those 3 cells: one candidate per row.
pair sumsmin-heap2461711nums2nums1357911131315179r1 c013r2 c0result12smallest is 3 → pair 1 of 3
popped(3, 0, 0)row 0, column 0
pair[1, 2]1 + 2 = 3
result size1of k = 3
The heap minimum is 3 at row 0, column 0. Every untaken cell of a seeded row sits at or to the right of that row's heap entry, so nothing untaken can be smaller: this is the next smallest pair.
pair sumsmin-heap2461711nums2nums1357911131315175r0 c113r2 c09r1 c0result12row 0 moves right → 5 joins the heap
pushed(5, 0, 1)1 + 4
heap size3one entry per live row
Row 0's next candidate is the cell to the right, sum 5. Only the right neighbour is pushed: the cell below belongs to row 1, which already has its own entry, so no cell can enter the heap twice. It is also the new minimum, so it rose to the root.
pair sumsmin-heap2461711nums2nums1357911131315179r1 c013r2 c0result1214smallest is 5 → pair 2 of 3
popped(5, 0, 1)row 0, column 1
pair[1, 4]1 + 4 = 5
result size2of k = 3
The heap minimum is 5 at row 0, column 1. Every untaken cell of a seeded row sits at or to the right of that row's heap entry, so nothing untaken can be smaller: this is the next smallest pair.
pair sumsmin-heap2461711nums2nums1357911131315177r0 c213r2 c09r1 c0result1214row 0 moves right → 7 joins the heap
pushed(7, 0, 2)1 + 6
heap size3one entry per live row
Row 0's next candidate is the cell to the right, sum 7. Only the right neighbour is pushed: the cell below belongs to row 1, which already has its own entry, so no cell can enter the heap twice. It is also the new minimum, so it rose to the root.
pair sumsmin-heap2461711nums2nums1357911131315179r1 c013r2 c0result121416smallest is 7 → pair 3 of 3, row 0 used up
popped(7, 0, 2)row 0, column 2
pair[1, 6]1 + 6 = 7
result size3of k = 3
The heap minimum is 7 at row 0, column 2. Every untaken cell of a seeded row sits at or to the right of that row's heap entry, so nothing untaken can be smaller: this is the next smallest pair. Row 0 has no column 3, so it is used up and leaves the heap for good.
pair sumsmin-heap2461711nums2nums1357911131315179r1 c013r2 c0result121416done: 3 smallest pairs
result[1,2] [1,4] [1,6]
sums computed5of 9 cells
Done. Only 5 of the 9 sums were ever computed; the faded cells were never touched. On 10⁵ × 10⁵ inputs with k = 10⁴ that is the difference between about 2·10⁴ cells and 10¹⁰.
05

Common pitfalls

Building every pair, then sorting

✗ Wrong
pairs = sorted(
    ([u, v] for u in nums1 for v in nums2), key=sum
)
return pairs[:k]
✓ Right
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

✗ Wrong
heappush(heap, (nums1[i] + nums2[j + 1], i, j + 1))
heappush(heap, (nums1[i + 1] + nums2[j], i + 1, j))
✓ Right
# 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

✗ Wrong
new PriorityQueue<int[]>((a, b) ->
    (nums1[a[0]] + nums2[a[1]]) - (nums1[b[0]] + nums2[b[1]]))
✓ Right
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.

06

Edge cases

Repeated values

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.

k equals n·m

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.

nums1 shorter than k

min(k, len(nums1)) seeds every row; the loop then walks right along the rows until k pairs are out.

07

Complexity

Time
O(k log min(k, n))
Space
O(min(k, n))
The heap never holds more than one entry per seeded row, so at most 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).
08

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.