Find K Pairs with Smallest Sums solution explained
Find K Pairs with Smallest Sums gives two sorted arrays and asks for the k pairs, one number from each, whose sums are smallest. Picture the sums as a grid that grows to the right and downward, seed a min-heap with the first column, and each time you pop a pair, push its right-hand neighbor. Every pop is the next smallest sum, so k pops give the answer in O(k log min(k, m)) time.
By Evin JohnPublished 9 min read
The problem, in plain terms
You get two arrays of integers, each sorted from smallest to largest, and a number k. A pair takes one element from the first array and one from the second; pairs are told apart by position, so equal values at different positions make different pairs. Return the k pairs with the smallest sums. If there are fewer than k pairs in total, return all of them. Among pairs with equal sums, the order usually does not matter, but confirm that with the interviewer.
a = [1, 4, 9] b = [2, 3, 10] k = 4
sum grid (row = a[i], column = b[j]):
2 3 10
1 3 4 11
4 6 7 14
9 11 12 19
smallest four sums: 3, 4, 6, 7
answer: [1,2] [1,3] [4,2] [4,3]The grid view is the whole trick. Because both arrays are sorted, every row increases left to right and every column increases top to bottom. So the cell holding the next smallest sum must sit directly right of, or directly below, a cell already taken. You never need to look at the far corner until everything closer is gone.
Before coding, ask: can the arrays be empty? Can values be negative or repeated? Can k exceed m × n? If k is huge, say so out loud, because then the output itself is the cost and no algorithm can beat O(k).
What the interviewer wants to see
This is the cleanest example of a heap frontier: a priority queue holding the boundary of the explored region of an implicitly sorted structure. Recognizing it here unlocks a whole group of problems, including merging k sorted lists and finding the k-th smallest element of a sorted matrix. The interviewer also checks that you avoid pushing the same cell twice.
Brute force: build and sort every pair
List all m × n pairs, sort them by sum, and take the first k. It is correct and quick to write, which makes it the reference for testing, but it costs O(m × n log(m × n)) time and O(m × n) memory even when k is 1.
def k_smallest_pairs_slow(a, b, k):
pairs = [[x, y] for x in a for y in b]
pairs.sort(key=lambda p: p[0] + p[1])
return pairs[:k]Optimal approach: walk the grid with a min-heap
Start with the first column: push (a[i] + b[0], i, 0) for each row i, but only for the first k rows, since a row further down cannot contribute anything when k cells above it in the first column are all smaller or equal. Then repeat k times: pop the smallest sum, record the pair, and if that row has a next column, push (a[i] + b[j + 1], i, j + 1). Each row moves right one step at a time, so no cell is ever pushed twice.
import heapq
def k_smallest_pairs(a, b, k):
if not a or not b:
return []
heap = [(a[i] + b[0], i, 0) for i in range(min(k, len(a)))]
heapq.heapify(heap)
out = []
while heap and len(out) < k:
_, i, j = heapq.heappop(heap)
out.append([a[i], b[j]])
if j + 1 < len(b):
heapq.heappush(heap, (a[i] + b[j + 1], i, j + 1))
return outAn equally valid version starts with only the corner (0, 0) and pushes both the right and the lower neighbor of each popped cell. That version needs a visited set, because a cell can be reached from its left and from above. Seeding the first column and only moving right avoids the set entirely, which is why it is the more common answer.
JavaScript has no built-in priority queue, so the version below carries a small binary heap of [sum, i, j] triples. In an interview, it is usually fine to say you would use a library heap and write only the frontier logic; be ready to write the heap if asked.
function kSmallestPairs(a, b, k) {
const out = [];
if (a.length === 0 || b.length === 0) return out;
const heap = [];
const less = (x, y) => x[0] < y[0];
const push = (item) => {
heap.push(item);
let c = heap.length - 1;
while (c > 0) {
const p = (c - 1) >> 1;
if (!less(heap[c], heap[p])) break;
[heap[c], heap[p]] = [heap[p], heap[c]];
c = p;
}
};
const pop = () => {
const top = heap[0];
const last = heap.pop();
if (heap.length > 0) {
heap[0] = last;
let p = 0;
for (;;) {
const l = 2 * p + 1, r = l + 1;
let m = p;
if (l < heap.length && less(heap[l], heap[m])) m = l;
if (r < heap.length && less(heap[r], heap[m])) m = r;
if (m === p) break;
[heap[m], heap[p]] = [heap[p], heap[m]];
p = m;
}
}
return top;
};
for (let i = 0; i < Math.min(k, a.length); i++) push([a[i] + b[0], i, 0]);
while (heap.length > 0 && out.length < k) {
const [, i, j] = pop();
out.push([a[i], b[j]]);
if (j + 1 < b.length) push([a[i] + b[j + 1], i, j + 1]);
}
return out;
}Complexity summary
| Approach | Time | Extra memory | Note |
|---|---|---|---|
| Sort all pairs | O(mn log mn) | O(mn) | Simple reference |
| Corner seed, two neighbors, visited set | O(k log k) | O(k) | Correct, slightly more bookkeeping |
| First-column seed, move right only | O(k log min(k, m)) | O(min(k, m)) | Expected answer |
Edge cases to try
- k larger than m × n: return every pair, and the loop must stop when the heap empties.
- One array of length 1: the answer walks along the other array.
- Repeated values, such as a = [1, 1]: both copies form separate pairs.
- Negative numbers: nothing changes, since only order matters.
- Equal sums at the boundary of k: either pair is a valid answer in most versions of the problem.
- An empty array: return an empty list instead of reading b[0].
Mistakes to avoid
- Seeding every row of a when a is huge and k is small, which wastes O(m) time and memory.
- Pushing both neighbors without a visited set, which produces duplicate pairs.
- Using two pointers that advance in a and b alternately. That misses pairs such as (a[0], b[2]) when they beat (a[1], b[1]).
- Storing values instead of indexes in the heap, then failing to find the next column.
- Assuming the output for equal sums must match one exact order, and writing extra tie-breaking that nobody asked for.
Follow-ups
- Only the k-th smallest sum is needed. The same frontier works; return the sum of the k-th pop. For large k, binary search on the sum with a two-pointer count is O((m + n) log range).
- Three arrays instead of two. Combine two arrays into their k smallest sums first, then pair that list with the third. Each step is the same problem.
- Largest sums instead. Walk from the bottom-right corner with a max-heap, or negate everything.
- The arrays are not sorted. Sort them first; the frontier argument depends on sorted rows and columns.
- Merge k sorted lists. Same idea: a heap holding one current element per list, replaced by its successor after each pop.
How to explain it out loud
Fictional example
- Candidate
- If I lay the sums out in a grid, rows follow a and columns follow b, and both directions are increasing because the arrays are sorted.
- Candidate
- So the next smallest sum is always adjacent to something I have already taken. I can keep the boundary in a min-heap and expand it one cell at a time.
- Candidate
- To avoid duplicates, I seed the first column for the first k rows, and each pop pushes only the cell to its right.
- Interviewer
- Why only k rows?
- Candidate
- Row k and below start at a sum no smaller than the k cells above them in the first column, so they cannot make the top k. That keeps the heap at most k entries and the time at O(k log k) or better.
Related problems
K-th Smallest Prime Fraction is the same frontier on a grid of fractions, and it also has a binary-search answer worth comparing. Merge Two Sorted Lists is the two-list base case of the merge-k follow-up. Minimum Cost to Hire K Workers uses a heap in a different way, to keep the best k items. Logger Rate Limiter is a lighter design question if you want a break from heaps.
Practicing it with Natively
Frontier problems are easiest when you can see the grid, so practice drawing it before you code. On Mac or Windows, Natively can read the arrays and the question from a screenshot in a practice session and suggest the first-column seeding with its complexity, and it keeps a transcript of the mock round so you can see whether you explained why duplicates cannot happen. The AI coding interview helper page shows how.
Questions people ask
How do you solve Find K Pairs with Smallest Sums?
Push (a[i] + b[0], i, 0) for the first min(k, len(a)) rows into a min-heap. Pop the smallest k times, recording each pair and pushing the next pair in the same row, (i, j + 1), when it exists.
What is the time complexity of Find K Pairs with Smallest Sums?
O(k log min(k, m)) time and O(min(k, m)) heap memory, where m is the length of the first array. Sorting every pair is O(mn log mn).
How do you avoid duplicate pairs in Find K Pairs with Smallest Sums?
Seed the heap with the first column and only ever push the cell to the right of a popped cell. Each cell then has exactly one way in. If you push both right and down neighbors, keep a visited set.
Why does the heap give pairs in order of sum?
Both arrays are sorted, so the sum grid increases along every row and column. The next smallest sum is always next to a cell already taken, which means it is already in the heap when it is needed.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
