Find K Pairs with Smallest Sums - Problem

You are given two integer arrays nums1 and nums2 sorted in non-decreasing order and an integer k.

Define a pair (u, v) which consists of one element from the first array and one element from the second array.

Return the k pairs (u₁, v₁), (u₂, v₂), ..., (uₖ, vₖ) with the smallest sums.

Input & Output

Example 1 — Basic Case
$ Input: nums1 = [1,7,11], nums2 = [2,4,6], k = 3
Output: [[1,2],[1,4],[1,6]]
💡 Note: The first 3 pairs with smallest sums are: (1,2)→3, (1,4)→5, (1,6)→7. All pairs from nums1[0] have the smallest possible sums.
Example 2 — Mixed Selection
$ Input: nums1 = [1,1,2], nums2 = [1,2,3], k = 2
Output: [[1,1],[1,1]]
💡 Note: The pairs with smallest sums are: (1,1)→2 and (1,1)→2. Both nums1[0] and nums1[1] paired with nums2[0] give the minimum sum.
Example 3 — Single Elements
$ Input: nums1 = [1,2], nums2 = [3], k = 3
Output: [[1,3],[2,3]]
💡 Note: Only 2 pairs are possible: (1,3)→4 and (2,3)→5. Since k=3 but only 2 pairs exist, we return all available pairs.

Constraints

  • 1 ≤ nums1.length, nums2.length ≤ 105
  • -109 ≤ nums1[i], nums2[i] ≤ 109
  • nums1 and nums2 both are sorted in non-decreasing order
  • 1 ≤ k ≤ 104

Visualization

Tap to expand
Find K Pairs with Smallest Sums INPUT nums1 (sorted) 1 7 11 nums2 (sorted) 2 4 6 k = 3 All Possible Pair Sums: 3 5 7 9 11 13 13 15 17 1 7 11 2 4 6 nums1=[1,7,11] nums2=[2,4,6] ALGORITHM STEPS 1 Initialize Min-Heap Push (nums1[0]+nums2[0], 0, 0) 2 Pop Smallest Sum Extract min pair from heap 3 Add to Result Store pair in output list 4 Push Next Candidates Add adjacent pairs to heap Min-Heap State: 3 9 5 Root always has min sum FINAL RESULT K = 3 Smallest Pairs: Pair 1: [1, 2] Sum = 3 (smallest) Pair 2: [1, 4] Sum = 5 (2nd smallest) Pair 3: [1, 6] Sum = 7 (3rd smallest) Output: [[1,2],[1,4],[1,6]] OK - Complete! 3 pairs returned as required Key Insight: Use a Min-Heap to efficiently track the next smallest sum without generating all pairs. Since arrays are sorted, if (i,j) is extracted, candidates (i+1,j) and (i,j+1) may be next smallest. Time Complexity: O(k log k) | Space Complexity: O(k) TutorialsPoint - Find K Pairs with Smallest Sums | Optimal Solution (Min-Heap Approach)
Asked in
Google 45 Amazon 32 Microsoft 28
142.5K Views
Medium Frequency
~25 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen