Find K Pairs with Smallest Sums
Master this topic with zero to advance depth.
Find K Pairs with Smallest Sums
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 nums1 and one element from nums2.
Return the k pairs (u1, v1), (u2, v2), ..., (uk, vk) with the smallest sums.
Visual Representation
nums1 = [1, 7, 11], nums2 = [2, 4, 6], k = 3
Possible Pairs:
(1,2) sum=3
(1,4) sum=5
(1,6) sum=7
(7,2) sum=9 ...
Smallest 3 pairs: [[1,2], [1,4], [1,6]]Examples
Level I: Brute Force + Sorting
Intuition
Generate all possible pairs from the two arrays, calculate their sums, and sort them. Return the first k pairs.
Thought Process
- Nest two loops to iterate over
nums1andnums2. - Store each pair and its sum in a list.
- Sort the list by sum.
- Take the first
kelements.
Detailed Dry Run
nums1 = [1,2], nums2 = [3], k = 1
- Pairs: [[1,3] sum:4, [2,3] sum:5]
- Sorted: [[1,3], [2,3]]
- Result: [[1,3]]
Level II: Max-Heap of size K (Better Brute Force)
Intuition
Instead of storing all pairs and sorting, we can maintain a Max-Heap of size . If we find a pair smaller than the root of our Max-Heap, we replace the root. This reduces space complexity for large if is small.
Thought Process
- Use a Max-Heap to store
[u, v]pairs based on their sum. - Iterate through
nums1andnums2(limit to to avoid unnecessary checks). - Push each pair to the heap.
- If heap size exceeds , pop the largest (root).
- Return all pairs in the heap.
Detailed Dry Run
nums1 = [1, 2], nums2 = [3], k = 1
- Pair [1,3], sum 4. Heap: [[1,3]]
- Pair [2,3], sum 5. Heap: [[2,3], [1,3]] -> Pop [2,3]. Heap: [[1,3]] Result: [[1,3]]
Level III: Min-Heap (Optimal)
Intuition
Since arrays are sorted, the smallest pair is (nums1[0], nums2[0]). The next candidates are (nums1[1], nums2[0]) or (nums1[0], nums2[1]). We can use a Min-Heap to explore pairs efficiently.
Thought Process
- Push
(nums1[i], nums2[0], 0)for alli(or justi=0and expand both ways) into a Min-Heap. - In each step, pop the smallest pair
(nums1[i], nums2[j]). - Add it to result.
- Push the next potential pair
(nums1[i], nums2[j+1])into the heap. - Repeat
ktimes.
Detailed Dry Run
nums1 = [1, 7, 11], nums2 = [2, 4, 6], k = 3
- Heap: [(1,2,idx_in_nums2=0)]
- Pop (1,2). Result: [[1,2]]. Push next in nums2: (1,4,1). Heap: [(1,4,1)]
- Pop (1,4). Result: [[1,2],[1,4]]. Push next: (1,6,2). Heap: [(1,6,2), (7,2,0)] (Note: 7,2 is pushed later or initialized) Actually simpler: Push all nums1[i] + nums2[0].
- Heap: [(1+2, 0,0), (7+2, 1,0), (11+2, 2,0)]
- Pop (3, 0,0). Result [[1,2]]. Push (1+4, 0,1).
- Pop (5, 0,1). Result [[1,2], [1,4]]. Push (1+6, 0,2).
- Pop (7, 0,2). Result [[1,2], [1,4], [1,6]]. Done.
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.