Magicsheet logo

Find K Pairs with Smallest Sums

Medium
53.4%
Updated 6/1/2025

Find K Pairs with Smallest Sums

What is this problem about?

The Find K Pairs with Smallest Sums interview question asks you to find kk pairs of numbers (u,v)(u, v) such that uu is from a sorted array nums1 and vv is from a sorted array nums2. The pairs should be selected to have the smallest possible sums. You need to return these kk pairs as a list of lists.

Why is this asked in interviews?

This is a high-signal problem for companies like Amazon, Meta, and Google. It tests your ability to handle multiple sorted streams and optimize a selection process. While you could generate all NimesMN imes M pairs and sort them (O(NMlog(NM))O(NM \log(NM))), the requirement is to find only kk pairs efficiently. It evaluations your mastery of the Heap (Priority Queue) interview pattern, specifically for merging sorted lists.

Algorithmic pattern used

This problem uses a Min-Heap (Priority Queue).

  1. Since the arrays are sorted, the smallest possible pair is always (nums1[0], nums2[0]).
  2. Initialize a Min-Heap with pairs (nums1[i], nums2[0]) for all ii up to min(k,n1)\min(k, n1).
  3. For kk iterations:
    • Pop the pair with the smallest sum from the heap.
    • Add it to the result list.
    • If the popped pair was (nums1[i], nums2[j]) and j+1<n2j+1 < n2, push the next possible pair from that row (nums1[i], nums2[j+1]) into the heap. This ensures you only explore the most promising candidates at each step.

Example explanation

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

  1. Heap: {(1+2, 0, 0), (7+2, 1, 0), (11+2, 2, 0)}.
  2. Pop (1, 2). Result: [[1, 2]]. Add next: (1, 4).
  3. Heap: {(1+4, 0, 1), (7+2, 1, 0), (11+2, 2, 0)}.
  4. Pop (1, 4). Result: [[1, 2], [1, 4]]. Add next: (1, 6).
  5. Heap: {(1+6, 0, 2), (7+2, 1, 0), (11+2, 2, 0)}.
  6. Pop (1, 6). Result: [[1, 2], [1, 4], [1, 6]]. Finished k=3k=3 pairs.

Common mistakes candidates make

  • Brute Force: Generating all NimesMN imes M pairs, which leads to Memory Limit Exceeded for large inputs.
  • Wrong Heap Initialization: Pushing only one pair initially, which can lead to missing better candidates from other "rows" of the pairing matrix.
  • Duplicate tracking: Using a Visited set for indices, which is O(k)O(k) extra space and unnecessary if you follow the "row-based" insertion logic.

Interview preparation tip

Think of this as "Merging kk Sorted Lists." Each element in nums1 starts a sorted list of pairs with nums2. Using a Min-Heap to find the smallest element across multiple sorted streams is a universal pattern for top-K problems.

Similar Questions