Find K Pairs with Smallest Sums
Given two integer arrays nums1 and nums2 sorted in ascending order and an integer k, find the k pairs (u, v) with u from nums1 and v from nums2 that have the smallest sums u + v. Return these k pairs.
Open official problem prompt ↗Produce the k pairs with the smallest sums, in ascending sum order, drawing one element from each sorted array without enumerating every possible pair.
Think of merging k sorted queues. Each row i of nums1 fixed against nums2 is its own increasing queue of sums. A single min-heap peeks at the front of every queue and always serves the globally smallest, advancing only that queue.
- Input
- nums1 = [1, 7, 11], nums2 = [2, 4, 6], k = 3
- Output
- [[1, 2], [1, 4], [1, 6]]
- Why
- The three smallest pair sums are 1+2=3, 1+4=5, and 1+6=7; all other pairs sum to at least 9.
1 <= nums1.length, nums2.length <= 10^5-10^9 <= nums1[i], nums2[i] <= 10^9nums1 and nums2 are sorted ascending1 <= k <= 10^4