Find K Pairs with Smallest Sums

Medium#373merge k lists

You get two arrays sorted in ascending order and a number k. A pair takes one number from each array. Return the k pairs with the smallest sums. Our example: [1, 4, 6], [2, 3, 9] and k = 4 — the answer is [1, 2], [1, 3], [4, 2] and [4, 3], with sums 3, 4, 6 and 7.

input
nums1, nums2: integers sorted in non-decreasing order, maybe with repeats; k: an integer.
returns
The k pairs [nums1[i], nums2[j]] with the smallest sums, each pair of indices (i, j) at most once, in any order. When several pairs have the same sum, any of them may be taken.
constraints
  • 1 ≤ nums1.length, nums2.length ≤ 1000
  • −10⁹ ≤ nums1[i], nums2[i] ≤ 10⁹
  • nums1 and nums2 are sorted in non-decreasing order
  • 1 ≤ k ≤ 1000
  • k ≤ nums1.length · nums2.length
our 14 tests keep to them
examples
Open a test in the tests panel: it shows the input and the expected answer.
/**
 * @param {number[]} nums1
 * @param {number[]} nums2
 * @param {number} k
 * @return {number[][]}
 */
function kSmallestPairs(nums1, nums2, k) {

}
Ctrl ↵
format
reset

saved in this browser

14 tests · limit 3 s

Stuck?

See the solution run step by step on our example, then why it works and its complexity.

Watch the walkthrough →

Next: more heap and top k problems

Pattern “Heap and top K” →

The problem and its statement belong to LeetCode. Here are our own retelling, example and solution. Patterns Hero is not affiliated with LeetCode.