← Questions
Find K pairs with the smallest sums
0
I was asked this
No reports yet. Sign in to say where you were asked it.
A coding interview question asked in Apple's technical phone screen and at Google and Meta, last asked Dec 2025. It tests heaps and arrays.
You get two integer arrays, nums1 and nums2, each sorted in non-decreasing order, and an integer k. A pair takes one number from each array. Return the k pairs with the smallest sums.
Interface
Unless you agree on a different interface with the interviewer, assume:
-
k_smallest_pairs(nums1: list[int], nums2: list[int], k: int) -> list[list[int]]: pairs in non-decreasing order of sum. If there are fewer thankpairs, return all of them.
Example
nums1 = [1, 7, 11], nums2 = [2, 4, 6], k = 3 -> [[1, 2], [1, 4], [1, 6]]
nums1 = [1, 1, 2], nums2 = [1, 2, 3], k = 2 -> [[1, 1], [1, 1]] # index pairs, so duplicates count
nums1 = [1, 2], nums2 = [3], k = 3 -> [[1, 3], [2, 3]]
Constraints
-
1 <= len(nums1), len(nums2) <= 10^5; values fit in 32-bit integers and may be negative. 1 <= k <= 10^4
Clarifying questions
- Are pairs counted by index, so equal values give separate pairs?
- How are ties in the sum ordered?
- What if
kis larger than the number of pairs?
What a strong answer covers
- Why building all
n × mpairs is too slow. - A min-heap seeded with
(nums1[i] + nums2[0], i, 0)for the firstmin(k, n)values ofi; each pop pushes(i, j + 1). O(k log k) time. - Why each pair enters the heap at most once with this scheme.
- Tests: duplicates,
klarger than the pair count, negative values.
Follow-ups
- Return only the k-th smallest sum, with less memory.
- The arrays are unsorted.
- Three arrays instead of two.
Where it's asked
- Apple · Technical phone screen · Last asked Dec 2025
- Google · First round: coding · Last asked Nov 202545 min · Coding in a Google Doc, no syntax highlighting or autocomplete · No AI
- Meta · AI-enabled coding · Last asked Sep 202560 min · Several progressive tasks on a starter codebase in CoderPad with an AI assistant panel; usually two rounds · The first task usually without AI, later tasks with it
What it tests
No official answer yet. Write yours on the right and run it.
Nothing published yet.
Sign in to submit your code; every attempt is kept here.
Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding


