Skip to content

Find K Pairs with Smallest Sums

MediumHeap / Priority Queue
Decode it first. Clues, constraints, pattern and plan before any code.

You get two arrays nums1 and nums2, both sorted in ascending order, and a number k. A pair [u, v] takes one number u from nums1 and one number v from nums2. Return the k pairs with the smallest sums. You can return them in any order.

nums1 = [1, 7, 11], nums2 = [2, 4, 6], k = 3  →  [[1, 2], [1, 4], [1, 6]]
nums1 = [1, 1, 2],  nums2 = [1, 2, 3], k = 2  →  [[1, 1], [1, 1]]

In the second example both 1s in nums1 pair with the 1 in nums2, so the pair [1, 1] appears twice. The tests are chosen so the set of answer pairs is unique.

Constraints

  • 1 <= nums1.length, nums2.length <= 10^5
  • -10^9 <= nums1[i], nums2[i] <= 10^9
  • 1 <= k <= 10^4
  • k <= nums1.length * nums2.length