15% off all plans & roadmaps Use code
See plansFind K Pairs with Smallest Sums
- LeetCode 373
- Medium
- Heap (Priority Queue) Patterns
- K-way Merge
Updated
TL;DR: You need the k smallest sums from two sorted arrays without building every pair. Seed a min-heap with the first pair of each row, then pop the smallest and push the next pair from the same row.
Problem
You receive two integer arrays, nums1 and nums2. Both arrays are sorted in non-decreasing order. You also receive an integer k.
A pair (u, v) takes one element u from nums1 and one element v from nums2. Find the k pairs with the smallest sums u + v. Return them as [[u1, v1], [u2, v2], ..., [uk, vk]].
Example 1
Input: nums1 = [1,7,11], nums2 = [2,4,6], k = 3 Output: [[1,2],[1,4],[1,6]] Explanation: The nine possible pairs have sums 3, 5, 7, 9, 11, 13, 13, 15 and 17. The three smallest sums belong to [1,2], [1,4] and [1,6].
Example 2
Input: nums1 = [1,1,2], nums2 = [1,2,3], k = 2 Output: [[1,1],[1,1]] Explanation: Both copies of 1 in nums1 pair with the 1 in nums2. That gives two pairs with sum 2, so both are returned.
Constraints
1 <= nums1.length, nums2.length <= 10^5-10^9 <= nums1[i], nums2[i] <= 10^9nums1andnums2are both sorted in non-decreasing order.1 <= k <= 10^4k <= nums1.length * nums2.length
Constraints that matter
- n and m up to 10^5 make the n * m pairs too many to build, so the solution must skip most of them.
- Sorted arrays mean each row (fixed u) is a sorted list, which allows a k-way merge.
- k up to 10^4 keeps the heap work near k log k, so the bound depends on k and not on n * m.
- Sums reach 2 * 10^9 and differences of sums reach 4 * 10^9, so compare sums directly or use 64-bit values.
Hints
Hint 1
The problem asks for the k smallest values among n * m sums, but you never need to look at most of them.
Hint 2
Start with the direct method.
Solution
Intuition
The problem asks for the k smallest values among n * m sums, but you never need to look at most of them. Both arrays are sorted, so for a fixed u the sums u + v grow as v grows.
Picture several sorted decks of cards, one deck per element of nums1, with a tray that holds only the top card of each deck. The tray is the min-heap, and each pop takes the smallest card off it and slides the next card from that same deck onto it.
Each row of the virtual grid, one row per element of nums1, is therefore already a sorted list. Finding the smallest sums across several sorted lists is the k-way merge pattern.
A min-heap runs the merge. Keep one candidate per row: the smallest pair in that row you have not used yet. The heap root is the smallest candidate overall. Pop it, record it, and push the next pair from the same row. Each pop yields the next smallest sum, so k pops give the answer.
The merge is correct because every untouched pair in row i is at least the current head of row i. The heap always holds the head of every row, so its root is the smallest untouched pair in the whole grid.
Worked example
Input: nums1 = [1, 2], nums2 = [3, 4], k = 10 Output: [[1, 3], [1, 4], [2, 3], [2, 4]] Explanation: There are only four pairs, with sums 4, 5, 5 and 6. The input asks for 10, which breaks the constraint k <= n * m, so the code returns all four pairs and stops when the heap runs empty.
Approach 1: Brute force: build and sort all pairs
Start with the direct method. Build every pair [u, v], sort all pairs by their sum, and return the first k. This method ignores that both arrays are sorted and that only k answers matter. It is still correct, because a full sort puts the k smallest sums first.
Steps
- Create an empty list
pairs. - For each u in nums1, and for each v in nums2, append
[u, v]topairs. - Sort
pairsby the value u + v. - Return the first min(k, len(pairs)) entries.
Dry run
Build the four pairs of the example in order: [1,3] with sum 4, [1,4] with sum 5, [2,3] with sum 5 and [2,4] with sum 6. The list is already in sum order, so the sort keeps it unchanged. Since k is 10 and only four pairs exist, the code returns all four. The output is [[1,3],[1,4],[2,3],[2,4]].
Complexity
| Time | O(nm log(nm)) |
|---|---|
| Space | O(nm) |
Let n be the length of nums1 and m the length of nums2. Two nested loops create n * m pairs, so building them costs O(nm) time and memory. Sorting N = nm pairs costs O(N log N), which is O(nm log(nm)). The sort dominates the time, and the list holds all nm pairs at once.
PythonTested in our runner
from typing import List, Optional
class Solution:
def kSmallestPairs(self, nums1: List[int], nums2: List[int], k: int) -> List[List[int]]:
# Build every pair, sort by sum, keep the first k
pairs = [[u, v] for u in nums1 for v in nums2]
pairs.sort(key=lambda p: p[0] + p[1])
return pairs[:k]JavaTested in our runner
import java.util.*;
class Solution {
public int[][] kSmallestPairs(int[] nums1, int[] nums2, int k) {
List<int[]> pairs = new ArrayList<>();
for (int u : nums1) {
for (int v : nums2) {
pairs.add(new int[]{u, v});
}
}
// Compare sums as long values to avoid int overflow
pairs.sort((a, b) -> Long.compare((long) a[0] + a[1], (long) b[0] + b[1]));
int total = Math.min(k, pairs.size());
int[][] result = new int[total][];
for (int t = 0; t < total; t++) {
result[t] = pairs.get(t);
}
return result;
}
}C++Tested in our runner
#include <algorithm>
#include <queue>
#include <tuple>
using namespace std;
class Solution {
public:
vector<vector<int>> kSmallestPairs(vector<int>& nums1, vector<int>& nums2, int k) {
vector<vector<int>> pairs;
for (int u : nums1) {
for (int v : nums2) {
pairs.push_back({u, v});
}
}
sort(pairs.begin(), pairs.end(), [](const vector<int>& a, const vector<int>& b) {
return (long long)a[0] + a[1] < (long long)b[0] + b[1];
});
if (k > (int)pairs.size()) k = pairs.size();
pairs.resize(k);
return pairs;
}
};JavaScriptTested in our runner
/**
* @param {number[]} nums1
* @param {number[]} nums2
* @param {number} k
* @return {number[][]}
*/
var kSmallestPairs = function(nums1, nums2, k) {
const pairs = [];
for (const u of nums1) {
for (const v of nums2) {
pairs.push([u, v]);
}
}
pairs.sort((a, b) => (a[0] + a[1]) - (b[0] + b[1]));
return pairs.slice(0, k);
};GoTested in our runner
import "sort"
func kSmallestPairs(nums1 []int, nums2 []int, k int) [][]int {
pairs := make([][]int, 0, len(nums1)*len(nums2))
for _, u := range nums1 {
for _, v := range nums2 {
pairs = append(pairs, []int{u, v})
}
}
sort.Slice(pairs, func(a, b int) bool {
return pairs[a][0]+pairs[a][1] < pairs[b][0]+pairs[b][1]
})
if k > len(pairs) {
k = len(pairs)
}
return pairs[:k]
}C#Tested in our runner
public class Solution {
public int[][] kSmallestPairs(int[] nums1, int[] nums2, int k) {
var pairs = new List<int[]>();
foreach (int u in nums1) {
foreach (int v in nums2) {
pairs.Add(new int[] { u, v });
}
}
pairs.Sort((a, b) => ((long)a[0] + a[1]).CompareTo((long)b[0] + b[1]));
return pairs.Take(k).ToArray();
}
}The K-way Merge infographic is part of Pro
A one-page visual of the pattern: when it applies, the steps and the invariant to keep.
Unlock the infographicSolution pattern
K-way Merge
Part of Heap (Priority Queue) Patterns
Approach 2: Min-heap k-way mergeOptimalK-way Merge
What's slow: the brute force builds and sorts n * m pairs, even though only k answers matter. The insight that fixes it is that row i, the pairs that start with nums1[i], is a sorted list because nums2 is sorted. Merge the rows with a min-heap that holds the current head of each row.
Rows at index k or later never matter. Each earlier row already has a first pair no larger than nums1[i] + nums2[0], so those rows can be skipped.
Steps
- Let h = min(n, k). Push
(nums1[i] + nums2[0], i, 0)for each i from 0 to h - 1. - Heapify the list so the smallest sum sits at the root.
- While the result has fewer than k pairs and the heap is not empty, pop the smallest
(sum, i, j). - Append
[nums1[i], nums2[j]]to the result. - If j + 1 < m, push
(nums1[i] + nums2[j+1], i, j+1). - Return the result.
Dry run
Seed the heap with rows 0 and 1, since min(2, 10) = 2. The heap holds (4,0,0) and (5,1,0). The table below tracks each step on the example.
| Step | Heap before pop (sum, i, j) | Pop | Result after step | Push |
|---|---|---|---|---|
| Seed | (4,0,0), (5,1,0) | none | [] | none |
| 1 | (4,0,0), (5,1,0) | (4,0,0) | [[1,3]] | (5,0,1) |
| 2 | (5,0,1), (5,1,0) | (5,0,1), since 0 < 1 breaks the tie | [[1,3],[1,4]] | none, because j + 1 = 2 is not below m = 2 |
| 3 | (5,1,0) | (5,1,0) | [[1,3],[1,4],[2,3]] | (6,1,1) |
| 4 | (6,1,1) | (6,1,1) | [[1,3],[1,4],[2,3],[2,4]] | none |
| End | empty | none | four pairs | stop, since the heap is empty |
The output is [[1,3],[1,4],[2,3],[2,4]]. The loop ends when the heap empties, not at k, because the example asks for more pairs than exist.
Complexity
| Time | O(k log k) |
|---|---|
| Space | O(k) |
Let n and m be the lengths of nums1 and nums2, and set h = min(n, k). Seeding and heapify take O(h), and h is at most k. Each iteration removes one entry and adds at most one, so the heap never holds more than h entries.
There are at most k iterations, each costing O(log h), so the loop takes O(k log k) time. The heap uses O(h) memory, and the output uses O(k).
PythonTested in our runner
import heapq
from typing import List, Optional
class Solution:
def kSmallestPairs(self, nums1: List[int], nums2: List[int], k: int) -> List[List[int]]:
n, m = len(nums1), len(nums2)
# One candidate per row: the first pair of each of the first min(n, k) rows
heap = [(nums1[i] + nums2[0], i, 0) for i in range(min(n, k))]
heapq.heapify(heap)
result = []
while heap and len(result) < k:
_, i, j = heapq.heappop(heap)
result.append([nums1[i], nums2[j]])
# Advance only within row i
if j + 1 < m:
heapq.heappush(heap, (nums1[i] + nums2[j + 1], i, j + 1))
return resultJavaTested in our runner
import java.util.*;
class Solution {
public int[][] kSmallestPairs(int[] nums1, int[] nums2, int k) {
int n = nums1.length, m = nums2.length;
// Each entry is {sum, i, j}; sums are stored as long to avoid overflow
PriorityQueue<long[]> heap = new PriorityQueue<>((a, b) -> Long.compare(a[0], b[0]));
for (int i = 0; i < Math.min(n, k); i++) {
heap.offer(new long[]{(long) nums1[i] + nums2[0], i, 0});
}
int[][] result = new int[k][];
int count = 0;
while (count < k && !heap.isEmpty()) {
long[] top = heap.poll();
int i = (int) top[1], j = (int) top[2];
result[count++] = new int[]{nums1[i], nums2[j]};
if (j + 1 < m) {
heap.offer(new long[]{(long) nums1[i] + nums2[j + 1], i, j + 1});
}
}
return Arrays.copyOf(result, count);
}
}C++Tested in our runner
#include <algorithm>
#include <queue>
#include <tuple>
using namespace std;
class Solution {
public:
vector<vector<int>> kSmallestPairs(vector<int>& nums1, vector<int>& nums2, int k) {
typedef tuple<long long, int, int> Item;
priority_queue<Item, vector<Item>, greater<Item>> heap;
int n = nums1.size(), m = nums2.size();
for (int i = 0; i < min(n, k); i++) {
heap.push(Item((long long)nums1[i] + nums2[0], i, 0));
}
vector<vector<int>> result;
while (!heap.empty() && (int)result.size() < k) {
Item top = heap.top();
heap.pop();
int i = get<1>(top), j = get<2>(top);
result.push_back({nums1[i], nums2[j]});
if (j + 1 < m) {
heap.push(Item((long long)nums1[i] + nums2[j + 1], i, j + 1));
}
}
return result;
}
};JavaScriptTested in our runner
/**
* @param {number[]} nums1
* @param {number[]} nums2
* @param {number} k
* @return {number[][]}
*/
var kSmallestPairs = function(nums1, nums2, k) {
const n = nums1.length, m = nums2.length;
const heap = [];
const less = (a, b) => a[0] < b[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;
while (true) {
const l = 2 * p + 1, r = l + 1;
let s = p;
if (l < heap.length && less(heap[l], heap[s])) s = l;
if (r < heap.length && less(heap[r], heap[s])) s = r;
if (s === p) break;
[heap[p], heap[s]] = [heap[s], heap[p]];
p = s;
}
}
return top;
};
for (let i = 0; i < Math.min(n, k); i++) {
push([nums1[i] + nums2[0], i, 0]);
}
const result = [];
while (heap.length > 0 && result.length < k) {
const [, i, j] = pop();
result.push([nums1[i], nums2[j]]);
if (j + 1 < m) {
push([nums1[i] + nums2[j + 1], i, j + 1]);
}
}
return result;
};GoTested in our runner
import "container/heap"
type kPairItem struct {
sum, i, j int
}
type kPairHeap []kPairItem
func (h kPairHeap) Len() int { return len(h) }
func (h kPairHeap) Less(a, b int) bool { return h[a].sum < h[b].sum }
func (h kPairHeap) Swap(a, b int) { h[a], h[b] = h[b], h[a] }
func (h *kPairHeap) Push(x interface{}) { *h = append(*h, x.(kPairItem)) }
func (h *kPairHeap) Pop() interface{} {
old := *h
n := len(old)
item := old[n-1]
*h = old[:n-1]
return item
}
func kSmallestPairs(nums1 []int, nums2 []int, k int) [][]int {
n, m := len(nums1), len(nums2)
limit := n
if k < limit {
limit = k
}
h := &kPairHeap{}
for i := 0; i < limit; i++ {
*h = append(*h, kPairItem{nums1[i] + nums2[0], i, 0})
}
heap.Init(h)
result := make([][]int, 0, k)
for len(result) < k && h.Len() > 0 {
top := heap.Pop(h).(kPairItem)
result = append(result, []int{nums1[top.i], nums2[top.j]})
if top.j+1 < m {
heap.Push(h, kPairItem{nums1[top.i] + nums2[top.j+1], top.i, top.j + 1})
}
}
return result
}C#Tested in our runner
public class Solution {
public int[][] kSmallestPairs(int[] nums1, int[] nums2, int k) {
int n = nums1.Length, m = nums2.Length;
var heap = new PriorityQueue<(int i, int j), long>();
for (int i = 0; i < Math.Min(n, k); i++) {
heap.Enqueue((i, 0), (long)nums1[i] + nums2[0]);
}
var result = new List<int[]>();
while (result.Count < k && heap.Count > 0) {
var (i, j) = heap.Dequeue();
result.Add(new int[] { nums1[i], nums2[j] });
if (j + 1 < m) {
heap.Enqueue((i, j + 1), (long)nums1[i] + nums2[j + 1]);
}
}
return result.ToArray();
}
}Common mistakes
- Seeding every pair
(nums1[i] + nums2[j])into the heap at the start. The heap grows to n * m entries. Seed only the first pair of each row and advance inside a row when you pop. - Pushing
(nums1[i] + nums2[j+1], i, j+1)without the guardj + 1 < m. The index runs past the end ofnums2on exhausted rows. Check the bound before every push. - Comparing sums with subtraction, such as
a[0] - b[0]in a Java comparator. The difference of two sums can reach 4 * 10^9 and overflow a 32-bit int. UseInteger.compareorLong.compare. - Pushing both
(i+1, j)and(i, j+1)after each pop. Both neighbours overlap, so pairs repeat and skip order. Advance only along the row, which keeps each pair in the heap once. - Calling
heappoporpollon an empty heap whilekis still positive. This happens when k exceeds the number of pairs, as in the example with k = 10. Check that the heap is non-empty in the loop condition.
Edge cases
- nums1 = [5] and nums2 = [7] with k = 1 returns
[[5,7]]. The single row seeds one entry and the loop stops after one pop. - nums1 = [1,1,2] and nums2 = [1,2,3] with k = 2 returns
[[1,1],[1,1]]. Duplicate values are separate pairs and both count. - nums1 = [-5,-1] and nums2 = [-3,2] with k = 3 returns
[[-5,-3],[-1,-3],[-5,2]]. Negative sums sort the same way as positive ones. - nums1 = [1,2] and nums2 = [3,4] with k = 4 returns all four pairs in sum order. When k equals n * m, every pair is needed.
- nums1 = [-1000000000] and nums2 = [-1000000000] with k = 1 returns the single pair with sum -2 * 10^9. The sum still fits in a 32-bit int, but differences of sums do not.
- n = m = 10^5 with k = 10^4 seeds only the first 10^4 rows. Rows beyond k never reach the heap.
Follow-ups interviewers ask
- What if nums2 is not sorted?
- The row argument breaks, because u + v no longer grows with v. Sort a copy of nums2 first. The output holds values, not indices, so the sorted copy gives the same pairs. The sort adds O(m log m) time.
- Can you avoid the heap entirely?
- Yes. Binary search on the sum threshold S. For each S, count pairs with sum at most S using two pointers over the sorted arrays, which costs O(n + m). The search needs about 32 rounds for sums in the 2 * 10^9 range. Then list pairs below the threshold and fill the rest with pairs equal to it. The total is O((n + m) log C) time, where C is the value range.
- What if nums1 is too large to hold in memory?
- Only the first min(n, k) values of nums1 can contribute to the answer, since later rows never reach the top k. Keep that prefix and read nums2 by index. The heap then holds at most min(n, k) entries.
Find K Pairs with Smallest Sums FAQ
What is the time complexity of Find K Pairs with Smallest Sums?
The min-heap solution runs in O(k log k) time, where k is the requested count. The brute force method takes O(nm log(nm)) because it sorts all pairs. The heap bound does not depend on n * m, only on k and the seeding step over min(n, k) rows.
Why use a min-heap for Find K Pairs with Smallest Sums?
Each row is sorted, so the smallest unused pair overall is the smallest head among the rows. A min-heap returns that minimum in O(log h) time and accepts the next pair from the same row. The heap never holds more than min(n, k) entries.
Can Find K Pairs with Smallest Sums be solved in O(1) extra space?
Not with the heap approach, which keeps up to min(n, k) entries. The threshold binary search method uses O(1) extra space beyond the output, since it keeps only counters and two indices. The output itself still takes O(k) space.
Why does the verified example return four pairs when k is 10?
The input has only four pairs, so k = 10 breaks the constraint k <= n * m. The code returns every pair it can produce. The loop stops when the heap empties, so it does not fail.
Asked at
See which companies ask this — Pro
Related problems
- Design Twitter · same technique: K-way Merge
- Kth Smallest Element in a Sorted Matrix · same technique: K-way Merge
- Merge k Sorted Lists · same technique: K-way Merge
- Smallest Range Covering Elements from K Lists · same technique: K-way Merge
- Top K Frequent Elements · same pattern: Heap (Priority Queue) Patterns
- Meeting Rooms II · same pattern: Heap (Priority Queue) Patterns
- Kth Largest Element in an Array · same pattern: Heap (Priority Queue) Patterns
- K Closest Points to Origin · same pattern: Heap (Priority Queue) Patterns
- Reorganize String · same pattern: Heap (Priority Queue) Patterns
- Single-Threaded CPU · same pattern: Heap (Priority Queue) Patterns