Find K Pairs with Smallest Sums
1 approach, code in every language
Problem description
You are given two integer arrays sorted in non-decreasing order, nums1 and nums2, along with an integer k. A pair (u, v) is formed by taking one element u from nums1 and one element v from nums2.
Return the k pairs whose sums u + v are the smallest among all possible pairs.
Example 1
Input: nums1 = [1,7,11], nums2 = [2,4,6], k = 3
Output: [[1,2],[1,4],[1,6]]
The three smallest sums are 1+2=3, 1+4=5, and 1+6=7, all pairing the smallest value of nums1.
Example 2
Input: nums1 = [1,1,2], nums2 = [1,2,3], k = 2
Output: [[1,1],[1,1]]
Both 1s in nums1 pair with the leading 1 in nums2 to give sum 2, the two smallest sums.
Constraints
1 <= nums1.length, nums2.length <= 10^5-10^9 <= nums1[i], nums2[i] <= 10^9nums1 and nums2 are both sorted in non-decreasing order1 <= k <= 10^4k <= nums1.length * nums2.length
Create a free account to see the solution
You get the step-by-step animation, the intuition and clean code in every language. Free, no credit card.
After the pattern
Now solve one you haven't seen.
Smallest Coupled Trims is our own problem on the technique behind Find K Pairs with Smallest Sums: a new statement, so there's no answer to remember. Write it in your browser and run it against graded tests.
1,194 problems · 15,062 graded tests · free