Problem Description
Given two integer arrays nums1 and nums2 sorted in non-decreasing order and an integer k, return the k pairs (u, v) with the smallest sums where u is from nums1 and v is from nums2.
Key Insights
- Both arrays are sorted, making it possible to efficiently traverse and pick the smallest candidate pairs.
- A min-heap (priority queue) can be used to always access the next smallest sum pair.
- Instead of generating all possible pairs (which could be very large), we only generate candidates and push new pairs from nums2 as needed.
Space and Time Complexity
Time Complexity: O(k log(min(k, n1))) where n1 is the size of nums1, since we push at most min(k, n1) elements into the heap. Space Complexity: O(min(k, n1)) for storing the heap elements.
Solution
We use a min-heap (priority queue) to efficiently track and extract the pair with the smallest sum. Initially, we push pairs composed of each element in nums1 (up to k elements) paired with the first element of nums2. Each element in the heap is a tuple containing (sum, index in nums1, index in nums2). Every time we extract the smallest pair, we add the next pair from nums2 (if available) for that index in nums1. This approach ensures we always have the next smallest pair available and avoids creating all possible pairs upfront.