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
Understanding the Visualization
1
Input Arrays
Two sorted arrays nums1=[1,7,11] and nums2=[2,4,6], k=3
2
Find Pairs
Systematically find pairs with smallest sums
3
Output Result
Return first k pairs: [[1,2], [1,4], [1,6]]
Key Takeaway
🎯 Key Insight: Use a min-heap to efficiently explore pairs in ascending order of their sums, starting from the guaranteed minimum
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code