MediumArrayHeap (Priority Queue)

Find K Pairs with Smallest Sums

LeetCode
1 approach, code in all languages

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^9
  • nums1 and nums2 are both sorted in non-decreasing order
  • 1 <= k <= 10^4
  • k <= nums1.length * nums2.length
You've got the patterns

Patterns get you through the screen. Shipping gets you hired.

FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.

750+ engineers trained · frontend, backend, AWS & AI

August 15 · 0d left
Enroll Now