Find K Pairs with Smallest Sums - Problem
Find K Pairs with Smallest Sums
Imagine you're a data analyst tasked with finding the most cost-effective combinations from two sorted price lists! ๐ฐ
You are given two integer arrays
A pair
Goal: Return the
Example: If
Imagine you're a data analyst tasked with finding the most cost-effective combinations from two sorted price lists! ๐ฐ
You are given two integer arrays
nums1 and nums2, both sorted in non-decreasing order, and an integer k. Your mission is to find the k pairs with the smallest sums.A pair
(u, v) consists of one element u from the first array and one element v from the second array. The sum of a pair is simply u + v.Goal: Return the
k pairs (uโ, vโ), (uโ, vโ), ..., (uโ, vโ) with the smallest sums.Example: If
nums1 = [1,7,11] and nums2 = [2,4,6], the pair (1,2) has sum 3, which would be the smallest possible sum. Input & Output
example_1.py โ 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) with sum 3, (1,4) with sum 5, and (1,6) with sum 7. Since all pairs with nums1[0]=1 have the smallest possible sums, we return these first.
example_2.py โ Larger K
$
Input:
nums1 = [1,1,2], nums2 = [1,2,3], k = 2
โบ
Output:
[[1,1],[1,1]]
๐ก Note:
The first 2 pairs with smallest sums are: (1,1) with sum 2, and another (1,1) with sum 2. Both use the first element from nums1 and the first element from nums2.
example_3.py โ K Exceeds Total Pairs
$
Input:
nums1 = [1,2], nums2 = [3], k = 3
โบ
Output:
[[1,3],[2,3]]
๐ก Note:
Only 2 pairs are possible: (1,3) with sum 4 and (2,3) with sum 5. Since k=3 exceeds the total number of pairs, 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
Start with Cheapest Base
Begin with the cheapest appetizer paired with all main courses - these are your initial candidates
2
Pick Best Available
Always choose the combination with the lowest current total cost
3
Smart Expansion
When you pick a combination, add the next pricier appetizer with the same main course as a new candidate
4
Repeat Until Complete
Continue until you've found k combinations - no need to check all possibilities!
Key Takeaway
๐ฏ Key Insight: By using a min-heap and leveraging the sorted nature of both arrays, we only explore the most promising combinations, achieving O(k*log(min(k,m))) complexity instead of O(m*n*log(m*n)) for the brute force approach!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code