You are given two arrays of whole numbers, nums1 and nums2, both sorted from smallest to largest, and a number k. A pair takes one number from nums1 and one from nums2; its sum is the two added together.
Return the k pairs whose sums are smallest, as [u, v] lists. They may come back in any order. Equal values at different positions make different pairs.
Example 1
Input: nums1 = [2, 3, 8], nums2 = [1, 4, 6], k = 4 Output: [[2, 1], [3, 1], [2, 4], [3, 4]] Why: their sums 3, 4, 6, 7 are the four smallest
2 more examples and the constraints
Example 2
Input: nums1 = [1, 1, 3], nums2 = [2, 5], k = 3 Output: [[1, 2], [1, 2], [3, 2]] Why: the two 1s each pair with 2 for a sum of 3
Example 3
Input: nums1 = [4], nums2 = [-1, 0], k = 2 Output: [[4, -1], [4, 0]] Why: there are only two pairs, so take both
Constraints
- 1 ≤ length of nums1, length of nums2 ≤ 100,000
- −1,000,000,000 ≤ every value ≤ 1,000,000,000
- 1 ≤ k ≤ 10,000, and k is at most the number of pairs
- Each array is sorted from smallest to largest (repeats allowed)
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Every pair, then sortO(mn log mn)
- Min-heap of next candidatesO(k log k)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 100,000 numbers each, k = 10,000 | Verdict |
|---|---|---|---|
| Every pair, then sort | O(mn log mn) | Too slow; too much memory | |
| Min-heap of next candidates | O(k log k) | Best; touches about 2k pairs |
m and n = the lengths of nums1 and nums2, k = pairs to return.
Edge cases to test
- k equals every pair. [4] with [-1, 0] and k = 2: the heap runs until both pairs are taken.
- Repeated values. Two 1s in nums1 make two separate [1, 2] pairs; both belong in the answer.
- nums1 longer than k. Seed only the first k values of nums1; the rest can never be among the k smallest.
- Huge values. 10⁹ + 10⁹ overflows a 32-bit int, so sums must be 64-bit.
Common mistakes
- Pushing both (i + 1, j) and (i, j + 1), which adds the same pair twice unless you track a visited set.
- Seeding every value of nums1 instead of the first k, which costs O(m log m) for nothing.
- Adding the sums in 32-bit integers, so large pairs wrap around to negative.
How to talk through it
- 1Clarify. Are both arrays sorted? Does order inside the answer matter? Do equal values at different positions count twice?
- 2Give the brute force. All m × n pairs, sorted; say it fails at ten billion pairs.
- 3See the rows. Each nums1[i] gives a sorted row of sums. Merging k sorted rows is a heap job.
- 4Code the heap. Seed the row heads, pop the smallest, push its right-hand neighbour. Mention the 64-bit sums.
- 5Test out loud. Run k equal to every pair, repeated values and one-element arrays before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?