Find K Pairs with Smallest Sums
Find K Pairs with Smallest Sums is a medium heaps problem solved with the advanced pattern.
The best approach, optimal (heap frontier, like merging k lists), runs in O(k log k) time and O(k) space.
Below are 2 approaches in Java, Python, C++ and JavaScript, from all pairs into a heap up.
Problem
Given two sorted arrays and k, return the k pairs (u, v) (one value from each array) with the smallest sums u + v.
Examples
Example 1
- Input
nums1 = [1, 7, 11], nums2 = [2, 4, 6], k = 3- Output
[[1,2],[1,4],[1,6]]
Example 2
- Input
nums1 = [1, 1, 2], nums2 = [1, 2, 3], k = 2- Output
[[1,1],[1,1]]
Constraints
1 <= nums1.length, nums2.length <= 10^5; both sorted ascending.1 <= k <= 10^4and k <= the total number of pairs.
Solve it here
Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.
Your own testcases: Run checks these, and the expected output comes from our reference solution.
My submissions
Nothing yet. Every Run and Submit you make while signed in shows up here.
| When | Result | Tests | Runtime | Your time | Type |
|---|
Run checks the testcases above (2 examples, or your own). Submit also runs 9 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.
Animated walkthrough
A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
Solutions
Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.
| Approach | Time | Space |
|---|---|---|
| All pairs into a heap | O(m · n · log k) | O(k) |
| Optimal (heap frontier, like merging k lists) | O(k log k) | O(k) |
1All pairs into a heap
O(m · n · log k)O(k)Generate every pair, keep a max-heap of size k, then output the heap.
- For each i, j: offer; poll when the size exceeds k.
class Solution {
public List<List<Integer>> kSmallestPairs(int[] nums1, int[] nums2, int k) {
PriorityQueue<int[]> heap = new PriorityQueue<>((a, b) -> Integer.compare(b[0] + b[1], a[0] + a[1]));
for (int x : nums1)
for (int y : nums2) {
heap.offer(new int[] { x, y });
if (heap.size() > k) heap.poll();
}
List<List<Integer>> out = new ArrayList<>();
while (!heap.isEmpty()) { int[] p = heap.poll(); out.add(0, Arrays.asList(p[0], p[1])); }
return out;
}
}class Solution:
def kSmallestPairs(self, nums1: List[int], nums2: List[int], k: int) -> List[List[int]]:
heap = [] # max-heap by sum: store (-(x + y), x, y)
for x in nums1:
for y in nums2:
heapq.heappush(heap, (-(x + y), x, y))
if len(heap) > k:
heapq.heappop(heap)
out = []
while heap:
_, x, y = heapq.heappop(heap)
out.insert(0, [x, y])
return outclass Solution {
public:
vector<vector<int>> kSmallestPairs(vector<int>& nums1, vector<int>& nums2, int k) {
auto cmp = [](const pair<int, int>& a, const pair<int, int>& b) { return a.first + a.second < b.first + b.second; };
priority_queue<pair<int, int>, vector<pair<int, int>>, decltype(cmp)> heap(cmp);
for (int x : nums1)
for (int y : nums2) {
heap.push({x, y});
if ((int)heap.size() > k) heap.pop();
}
vector<vector<int>> out;
while (!heap.empty()) { auto p = heap.top(); heap.pop(); out.insert(out.begin(), {p.first, p.second}); }
return out;
}
};class MinHeap {
constructor(cmp = (a, b) => a - b) { this.a = []; this.cmp = cmp; }
size() { return this.a.length; }
isEmpty() { return this.a.length === 0; }
peek() { return this.a[0]; }
push(x) {
const a = this.a;
a.push(x);
let i = a.length - 1;
while (i > 0) {
const p = (i - 1) >> 1;
if (this.cmp(a[i], a[p]) >= 0) break;
[a[i], a[p]] = [a[p], a[i]];
i = p;
}
}
pop() {
const a = this.a, top = a[0], last = a.pop();
if (a.length > 0) {
a[0] = last;
let i = 0;
while (true) {
const l = 2 * i + 1, r = l + 1;
let m = i;
if (l < a.length && this.cmp(a[l], a[m]) < 0) m = l;
if (r < a.length && this.cmp(a[r], a[m]) < 0) m = r;
if (m === i) break;
[a[i], a[m]] = [a[m], a[i]];
i = m;
}
}
return top;
}
}
function kSmallestPairs(nums1, nums2, k) {
const heap = new MinHeap((a, b) => (b[0] + b[1]) - (a[0] + a[1]));
for (const x of nums1)
for (const y of nums2) {
heap.push([x, y]);
if (heap.size() > k) heap.pop();
}
const out = [];
while (!heap.isEmpty()) { const p = heap.pop(); out.unshift([p[0], p[1]]); }
return out;
}2Optimal (heap frontier, like merging k lists)
O(k log k)O(k)Seed the heap with (i, 0) for the first min(k, m) rows. Each time you poll (i, j), push (i, j + 1), the next pair in that row. The heap never holds more than k entries, and you stop after k polls.
- Offer {nums1[i] + nums2[0], i, 0} for i < min(k, m).
- Repeat k times: poll {sum, i, j}; record the pair; if j + 1 < n, offer (i, j + 1).
class Solution {
public List<List<Integer>> kSmallestPairs(int[] nums1, int[] nums2, int k) {
PriorityQueue<int[]> heap = new PriorityQueue<>((a, b) -> Integer.compare(a[0], b[0]));
for (int i = 0; i < Math.min(k, nums1.length); i++) heap.offer(new int[] { nums1[i] + nums2[0], i, 0 });
List<List<Integer>> out = new ArrayList<>();
while (k-- > 0 && !heap.isEmpty()) {
int[] e = heap.poll();
int i = e[1], j = e[2];
out.add(Arrays.asList(nums1[i], nums2[j]));
if (j + 1 < nums2.length) heap.offer(new int[] { nums1[i] + nums2[j + 1], i, j + 1 });
}
return out;
}
}class Solution:
def kSmallestPairs(self, nums1: List[int], nums2: List[int], k: int) -> List[List[int]]:
heap = []
for i in range(min(k, len(nums1))):
heapq.heappush(heap, (nums1[i] + nums2[0], i, 0))
out = []
while k > 0 and heap:
k -= 1
_, i, j = heapq.heappop(heap)
out.append([nums1[i], nums2[j]])
if j + 1 < len(nums2):
heapq.heappush(heap, (nums1[i] + nums2[j + 1], i, j + 1))
return outclass Solution {
public:
vector<vector<int>> kSmallestPairs(vector<int>& nums1, vector<int>& nums2, int k) {
priority_queue<array<int, 3>, vector<array<int, 3>>, greater<array<int, 3>>> heap;
for (int i = 0; i < min(k, (int)nums1.size()); i++) heap.push({nums1[i] + nums2[0], i, 0});
vector<vector<int>> out;
while (k-- > 0 && !heap.empty()) {
array<int, 3> e = heap.top();
heap.pop();
int i = e[1], j = e[2];
out.push_back({nums1[i], nums2[j]});
if (j + 1 < (int)nums2.size()) heap.push({nums1[i] + nums2[j + 1], i, j + 1});
}
return out;
}
};class MinHeap {
constructor(cmp = (a, b) => a - b) { this.a = []; this.cmp = cmp; }
size() { return this.a.length; }
isEmpty() { return this.a.length === 0; }
peek() { return this.a[0]; }
push(x) {
const a = this.a;
a.push(x);
let i = a.length - 1;
while (i > 0) {
const p = (i - 1) >> 1;
if (this.cmp(a[i], a[p]) >= 0) break;
[a[i], a[p]] = [a[p], a[i]];
i = p;
}
}
pop() {
const a = this.a, top = a[0], last = a.pop();
if (a.length > 0) {
a[0] = last;
let i = 0;
while (true) {
const l = 2 * i + 1, r = l + 1;
let m = i;
if (l < a.length && this.cmp(a[l], a[m]) < 0) m = l;
if (r < a.length && this.cmp(a[r], a[m]) < 0) m = r;
if (m === i) break;
[a[i], a[m]] = [a[m], a[i]];
i = m;
}
}
return top;
}
}
function kSmallestPairs(nums1, nums2, k) {
const heap = new MinHeap((a, b) => a[0] - b[0]);
for (let i = 0; i < Math.min(k, nums1.length); i++) heap.push([nums1[i] + nums2[0], i, 0]);
const out = [];
while (k-- > 0 && !heap.isEmpty()) {
const e = heap.pop();
const i = e[1], j = e[2];
out.push([nums1[i], nums2[j]]);
if (j + 1 < nums2.length) heap.push([nums1[i] + nums2[j + 1], i, j + 1]);
}
return out;
}Edge cases to test
- k larger than one array's length
- Duplicate values
Hints
Hint 1
Picture a matrix where cell (i, j) = nums1[i] + nums2[j]. Rows and columns are sorted, so it is like merging k sorted lists.
FAQ
What is the best time complexity for Find K Pairs with Smallest Sums?
Optimal (heap frontier, like merging k lists) runs in O(k log k) time and O(k) extra space.
Which pattern does Find K Pairs with Smallest Sums use?
It is a heaps problem that uses the advanced pattern. Other problems with the same pattern: Find Median from Data Stream, Trapping Rain Water II, Minimum Number of Refueling Stops.
Is there a brute force solution for Find K Pairs with Smallest Sums?
Yes. All pairs into a heap takes O(m · n · log k) time and O(k) space. Generate every pair, keep a max-heap of size k, then output the heap.
Which edge cases should I test for Find K Pairs with Smallest Sums?
k larger than one array's length; Duplicate values.