Problem
Given two integer arrays sorted in non-decreasing order, return k pairs (u, v) with u from the first array and v from the second, that have the smallest sums.
Examples
Example 1
`nums1 = [1, 7, 11], nums2 = [2, 4, 6], k = 3``[[1, 2], [1, 4], [1, 6]]`Example 2
`nums1 = [1, 1, 2], nums2 = [1, 2, 3], k = 2``[[1, 1], [1, 1]]`Constraints
1 <= nums1.length, nums2.length <= 10^5-10^9 <= nums1[i], nums2[i] <= 10^9nums1andnums2both are sorted in non-decreasing order.1 <= k <= 10^4k <= nums1.length * nums2.length
Hints
Hint 1
A pair uses one value from each array. The same index can be reused in different pairs. If there are fewer than k possible pairs, return all of them.
Hint 2
The pair-sum grid is sorted in each row and column, so a best-first search with a min-heap finds the next pair the way merge-k or a sorted-matrix walk does.
Solution
Tried it yourself? The approach, complexity, and code stay hidden until you choose.
Approach
Brute force. Build every pair, sort by sum, and take the first k. That is O(n m log(n m)).
Optimal. Start the heap at (0, 0). When you pop (i, j), push (i, j+1) if it exists, and push (i+1, j) only when j is 0, which expands each row once and keeps the heap small. A visited set of (i, j) also works and is easier to explain.
Alternative. Binary search on the pair-sum threshold, then collect k pairs at or under that sum, is possible but more code.
Complexity
- Time
- O(k log k)
O(k log k) time if you seed at most k rows, and O(k) extra space. You never materialize the full n by m grid.
- Space
- O(k)
Code
import heapq
def k_smallest_pairs(nums1: list[int], nums2: list[int], k: int) -> list[list[int]]:
ans: list[list[int]] = []
heap: list[tuple[int, int, int]] = []
for i in range(min(len(nums1), k)):
heapq.heappush(heap, (nums1[i] + nums2[0], i, 0))
while heap and len(ans) < k:
_, i, j = heapq.heappop(heap)
ans.append([nums1[i], nums2[j]])
if j + 1 < len(nums2):
heapq.heappush(heap, (nums1[i] + nums2[j + 1], i, j + 1))
return ans
if __name__ == "__main__":
assert k_smallest_pairs([1, 7, 11], [2, 4, 6], 3) == [[1, 2], [1, 4], [1, 6]]
assert k_smallest_pairs([1, 1, 2], [1, 2, 3], 2) == [[1, 1], [1, 1]]
print("ok")import java.util.ArrayList;
import java.util.List;
import java.util.PriorityQueue;
public class FindKPairsWithSmallestSums {
static List<List<Integer>> kSmallestPairs(int[] nums1, int[] nums2, int k) {
var ans = new ArrayList<List<Integer>>();
var heap = new PriorityQueue<int[]>((a, b) -> Integer.compare(a[0], b[0]));
int n = nums1.length, m = nums2.length;
for (int i = 0; i < n && i < k; i++) heap.offer(new int[] {nums1[i] + nums2[0], i, 0});
while (!heap.isEmpty() && ans.size() < k) {
int[] cur = heap.poll();
int i = cur[1], j = cur[2];
ans.add(List.of(nums1[i], nums2[j]));
if (j + 1 < m) heap.offer(new int[] {nums1[i] + nums2[j + 1], i, j + 1});
}
return ans;
}
public static void main(String[] args) {
var a = kSmallestPairs(new int[] {1, 7, 11}, new int[] {2, 4, 6}, 3);
if (!a.equals(List.of(List.of(1, 2), List.of(1, 4), List.of(1, 6)))) throw new AssertionError(a);
var b = kSmallestPairs(new int[] {1, 1, 2}, new int[] {1, 2, 3}, 2);
if (!b.equals(List.of(List.of(1, 1), List.of(1, 1)))) throw new AssertionError(b);
System.out.println("ok");
}
}Edge cases
- Official samples: [1,7,11] and [2,4,6] with k = 3 return [1,2], [1,4], [1,6]; [1,1,2] and [1,2,3] with k = 2 return [1,1], [1,1].
- If k is larger than n times m, the loop stops when the heap is empty.
Follow-ups
- Kth Smallest Element in a Sorted Matrix uses the same best-first idea on a matrix that is sorted in rows and columns.
Interview script
"The pair-sum matrix is sorted in every row, so I start a min-heap with the first column and walk right along a row after I pop it. That yields the next best pair in log k time without building every pair."
Source: LeetCode 373: Find K Pairs with Smallest Sums Source: Java SE 17 API: PriorityQueue
Heap scheduling
Sources (2)
- LeetCode 373: Find K Pairs with Smallest Sumsleetcode.com
- Java SE 17 API: PriorityQueuedocs.oracle.com