SDE & MLE Prep

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