AAlgoLoopSpaced repetition for LeetCode
MEDIUMHeap / Priority QueueLeetCode ↗

Find K Pairs with Smallest Sums

The key idea

Both arrays are sorted, so the smallest sum is always nums1[0] + nums2[0]. Once you pop pair (i, j), the next candidates can only be (i+1, j) and (i, j+1). A min-heap keyed on the pair sum lets you greedily pull the next-smallest pair k times without generating all m*n pairs.

Problem

You are given two integer arrays nums1 and nums2 sorted in non-decreasing order and an integer k.

Define a pair (u, v) which consists of one element from the first array and one element from the second array.

Return the k pairs (u1, v1), (u2, v2), ..., (uk, vk) with the smallest sums.

Constraints

Examples

Input: nums1 = [1,7,11], nums2 = [2,4,6], k = 3 Output: [[1,2],[1,4],[1,6]]
Input: nums1 = [1,1,2], nums2 = [1,2,3], k = 2 Output: [[1,1],[1,1]]
Input: nums1 = [1,2], nums2 = [3], k = 3 Output: [[1,3],[2,3]]

Complexity

Time: O(k log k) Space: O(k)

See the full solution

410310
Step-by-step visualization
Start free →

More Heap / Priority Queue problems