InterviewPrepKit

Home / Coding / Heap & Priority Queue

Find K Pairs with Smallest Sums

medium Original β†—
Solving tips
  • Picture the mΓ—n sum grid; sorted inputs make every row and column non-decreasing, so run a best-first (Dijkstra-style) frontier instead of materializing it.
  • Seed a min-heap with (i, 0) for the first min(k, m) rows, then after popping (i, j) push only its right neighbor (i, j+1) β€” each row enters in order, so no visited set is needed.
  • Store indices (not just values) in the heap so you can advance rightward and keep index-distinct duplicate pairs separate.
  • Target O(k log k) time and O(k) space; stop when the heap empties to handle the 'fewer than k pairs' case.

Problem

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

A pair is one element from each array: (u, v) with u from nums1 and v from nums2. Different index positions count as different pairs even if the values repeat.

Return the k pairs with the smallest sums u + v, as a list of [u, v] pairs. If fewer than k pairs exist in total, return them all. Any order among equal sums is accepted.

Examples

  • nums1 = [1, 7, 11], nums2 = [2, 4, 6], k = 3 β†’ [[1, 2], [1, 4], [1, 6]] β€” sums 3, 5, 7 beat every pair starting with 7 or 11.
  • nums1 = [1, 1, 2], nums2 = [1, 2, 3], k = 2 β†’ [[1, 1], [1, 1]] β€” the two 1s in nums1 each form their own pair with nums2’s first 1 (sums 2 and 2).
  • nums1 = [1, 2], nums2 = [3], k = 10 β†’ [[1, 3], [2, 3]] β€” only 2 pairs exist, so return both.

Constraints

  • 1 <= len(nums1), len(nums2) <= 10^5
  • -10^9 <= nums1[i], nums2[i] <= 10^9
  • Both arrays sorted ascending
  • 1 <= k <= 10^4

With up to 10^10 total pairs, enumerating them all is off the table β€” the answer must cost roughly O(k log k).

Think about it first

Hint 1 Picture the m-by-n grid of sums `nums1[i] + nums2[j]`. Because both arrays are sorted, each row and each column of that grid is non-decreasing. Where must the overall smallest sum sit?
Hint 2 Once you take a pair `(i, j)`, which grid cells become newly "eligible" as candidates for the next-smallest sum? You never need to consider a cell before its left/up neighbor has been taken.
Hint 3 Min-heap frontier: seed with `(i, 0)` for the first `min(k, m)` rows. Pop the smallest sum, record it, and push only its right neighbor `(i, j + 1)`. Each row's cells enter in order, no visited-set needed, and you stop after k pops.
Your workspace Not runnable by design β€” this is your interview scratchpad. Saved on this device.