24 · Heaps & Priority Queues

#373 Find K Pairs with Smallest Sums

Mediumsolve on LeetCode ↗

frequently reported atLinkedInAmazonGoogle

the problem

In plain words

You get two integer arrays nums1 and nums2, both sorted in non-decreasing order, and an integer k. A pair takes one value from nums1 and one from nums2. Return the k pairs with the smallest sums, each written as [u, v]. Any order of the pairs is accepted.

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

out [[1,2],[1,4],[1,6]]

In sum order the pairs go [1,2]=3, [1,4]=5, [1,6]=7, [7,2]=9, … — take the first three.

in nums1 = [1,1,2], nums2 = [1,2,3], k = 2

out [[1,1],[1,1]]

The two 1s in nums1 are different elements, so [1,1] appears twice.

  • 1 ≤ nums1.length, nums2.length ≤ 10⁵
  • -10⁹ ≤ nums1[i], nums2[i] ≤ 10⁹
  • Both arrays are sorted in non-decreasing order
  • 1 ≤ k ≤ 10⁴ and k ≤ nums1.length · nums2.length

your turn

Try it before you peek

Read the examples, say the brute force out loud, then write code: here or on LeetCode ↗. Stuck for 20 minutes? Open one hint at a time.

Solve it in the browser

LeetCode-style: complete the class. Compiled by the real javac (Java 17) and judged right here — nothing is sent anywhere.

    Solutions are hidden so you can try first. Even 20 minutes of real effort makes the answer stick far better than reading it.

    Marking the problem solved, or opening every hint, also shows it.

    practise next

    Similar problems

    1. #23
    2. #632
    3. #167