Find K Pairs with Smallest Sums
MediumTop Interview 150 Heap / Priority QueueProblem
You are given two integer arrays nums1 and nums2, each sorted in ascending order, and an
integer k. A pair takes one number from each array: [nums1[u], nums2[v]].
Return the k pairs with the smallest sums, from smallest sum to largest. If there are
fewer than k pairs in total, return all of them.
Constraints
- 1 ≤ nums1.length, nums2.length ≤ 100 000
- −10^9 ≤ nums1[i], nums2[i] ≤ 10^9
- nums1 and nums2 are sorted in ascending order
- 1 ≤ k ≤ 10 000
Examples: pick one to animate
Solutions
Time: The heap starts with min(k, n) entries and never grows beyond that, because every pop pushes at most one entry. Each of the at most k pops and pushes costs O(log k).
Space: The heap holds at most min(k, n) entries, and the answer holds k pairs.
Picture a table where row u holds nums1[u] + nums2[0], nums1[u] + nums2[1], …. Every row is
sorted, so the next-smallest sum overall is the front of some row. Keep a min-heap with the front
of each row (only the first k rows can matter). Pop the smallest sum, record the pair, and push the
next pair from the same row. After k pops we have the answer, without ever looking at all n · m pairs.
The heap is an array the code manages itself, drawn here as array and tree.