Find K Pairs with Smallest Sums

MediumK-way Merge · Min-Heap🧩 K-Way MergeLeetCode #373 ↗Updated

Problem

You get two arrays nums1 and nums2, each sorted in non-decreasing order, and an integer k. A pair takes one element from each array. Return the k pairs [u, v] whose sums u + v are the smallest (any order; when sums tie, any valid choice is accepted).
Inputnums1 = [1,7,11], nums2 = [2,4,6], k = 3Output[[1,2],[1,4],[1,6]]
Inputnums1 = [1,1,2], nums2 = [1,2,3], k = 2Output[[1,1],[1,1]]

1 ≤ m, n ≤ 105  ·  -109 ≤ values ≤ 109  ·  1 ≤ k ≤ min(104, m·n)

Try it yourself

Java
class Solution {
    public List<List<Integer>> kSmallestPairs(int[] nums1, int[] nums2, int k) {
        
    }
}
Your code is saved in this browser.Submit on LeetCode ↗
Key insight
Picture an m×n grid of sums: every row i is sorted (nums1[i] + nums2[0..]). Taking the k smallest is a k-way merge of sorted rows — keep each row's next candidate in a min-heap and pop k times.
PatternK-Way Merge

Instinct Several sorted lists, rows or streams and you need the global order, the k-th smallest or a range: keep one cursor per list in a min-heap.

Memory hack Line up the heads, crown the smallest, then let its next-in-line step up.

Open the K-Way Merge guide →

Approaches

Brute ForceGenerate All Pairs, Sort by Sum

Time O(mn log(mn))Space O(mn)

Materialise every (i, j) pair, sort by nums1[i] + nums2[j] and keep the first k. Ignores the fact that both inputs are already sorted.

Java
public List<List<Integer>> kSmallestPairs(int[] nums1, int[] nums2, int k) {
    List<int[]> all = new ArrayList<>();
    for (int a : nums1) {
        for (int b : nums2) all.add(new int[]{a, b});
    }
    // Integer.compare avoids overflow of (sumA - sumB)
    all.sort((p, q) -> Integer.compare(p[0] + p[1], q[0] + q[1]));
    List<List<Integer>> res = new ArrayList<>();
    for (int i = 0; i < k; i++) res.add(List.of(all.get(i)[0], all.get(i)[1]));
    return res;
}

Up to 1010 pairs at the limits — only a reference answer.

At a glance

LevelApproachTimeSpace
Brute ForceGenerate All Pairs, Sort by SumO(mn log(mn))O(mn)
BetterBounded Max-Heap with Early BreaksO(min(m,k) · min(n,k) · log k)O(k)
OptimalK-way Merge with a Min-Heap of Row HeadsO(k log min(m, k))O(min(m, k))
Common pitfalls
  • Comparator (a, b) -> sumA - sumB overflows when sums span ±2·109.
  • Seeding both (i+1, j) and (i, j+1) without a visited set pushes duplicates.
  • Seeding all m rows: harmless for correctness but O(m) work when k is much smaller.
Interview tips
  • Draw the sum grid; sorted rows make the merge analogy obvious.
  • Mention it's the same skeleton as Merge k Sorted Lists (23) and Kth Smallest in a Sorted Matrix (378).
  • Clarify that ties may be returned in any order — tests should compare sums, not exact pairs.
Pattern
K-way merge → k smallest items across several sorted sequences (rows of a sorted grid).
My notes saved in this browser