373. Find K Pairs with Smallest Sums
Problem
nums1 and nums2 are sorted ascending. Return the k pairs [u, v], with u from nums1 and v from nums2, that have the smallest sums.
Example: nums1 = [1,7,11], nums2 = [2,4,6], k = 3 → [[1,2],[1,4],[1,6]]
Constraints: arrays up to 10⁵ long; k ≤ 10⁴.
Think of an implicit sorted matrix nums1[i] + nums2[j]. Seed the heap with (i, 0) for the first k rows; each pop pushes (i, j+1).
Complexity: O(k log k).
class Solution:
def kSmallestPairs(self, nums1: List[int], nums2: List[int], k: int) -> List[List[int]]:
h = [(nums1[i] + nums2[0], i, 0) for i in range(min(k, len(nums1)))]
heapify(h)
res = []
while h and len(res) < k:
_, i, j = heappop(h)
res.append([nums1[i], nums2[j]])
if j + 1 < len(nums2):
heappush(h, (nums1[i] + nums2[j + 1], i, j + 1))
return res
assert sorted(Solution().kSmallestPairs([1, 7, 11], [2, 4, 6], 3)) == sorted([[1, 2], [1, 4], [1, 6]])
assert sorted(Solution().kSmallestPairs([1, 1, 2], [1, 2, 3], 2)) == sorted([[1, 1], [1, 1]])
class Solution {
public List<List<Integer>> kSmallestPairs(int[] nums1, int[] nums2, int k) {
PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> a[0] - b[0]); // {sum, i, j}
for (int i = 0; i < Math.min(k, nums1.length); i++) pq.add(new int[]{nums1[i] + nums2[0], i, 0});
List<List<Integer>> res = new ArrayList<>();
while (!pq.isEmpty() && res.size() < k) {
int[] t = pq.poll();
int i = t[1], j = t[2];
res.add(List.of(nums1[i], nums2[j]));
if (j + 1 < nums2.length) pq.add(new int[]{nums1[i] + nums2[j + 1], i, j + 1});
}
return res;
}
}
type pair struct{ sum, i, j int }
type pairHeap []pair
func (h pairHeap) Len() int { return len(h) }
func (h pairHeap) Less(i, j int) bool { return h[i].sum < h[j].sum }
func (h pairHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
func (h *pairHeap) Push(x any) { *h = append(*h, x.(pair)) }
func (h *pairHeap) Pop() any {
old := *h
x := old[len(old)-1]
*h = old[:len(old)-1]
return x
}
func kSmallestPairs(nums1 []int, nums2 []int, k int) [][]int {
h := &pairHeap{}
for i := 0; i < min(k, len(nums1)); i++ { // (i, 0) for every row
heap.Push(h, pair{nums1[i] + nums2[0], i, 0})
}
res := [][]int{}
for h.Len() > 0 && len(res) < k {
p := heap.Pop(h).(pair)
res = append(res, []int{nums1[p.i], nums2[p.j]})
if p.j+1 < len(nums2) {
heap.Push(h, pair{nums1[p.i] + nums2[p.j+1], p.i, p.j + 1})
}
}
return res
}