Find K Pairs with Smallest Sums

Among all pairs (a, b) from two sorted arrays, return the k with the smallest sum — heap over the implicit grid.

Medium
Time O(k log k) Space O(k)
LeetCode
7 min read
k-way-merge heaps

Problem#

Two sorted ascending arrays nums1, nums2. Return the k pairs (nums1[i], nums2[j]) with smallest sums.

Examples#

  • nums1 = [1,7,11], nums2 = [2,4,6], k = 3[[1,2],[1,4],[1,6]]

Constraints#

  • 1 <= nums1.length, nums2.length <= 10^4.

Hints#

Hint 1
Treat the grid of all pairs as an implicit graph. Start at (0,0); each popped (i,j) unlocks (i+1,j) and (i,j+1). Avoid duplicates with a visited set.

Approach#

Min-heap over (sum, i, j). Push (0, 0) initially. Each pop generates the next-smallest pair; push (i+1, j) and (i, j+1) if not visited.

Solution#

Find K Pairs with Smallest Sums
class Solution {
public:
vector<vector<int>> kSmallestPairs(vector<int>& a, vector<int>& b, int k) {
priority_queue<tuple<int,int,int>, vector<tuple<int,int,int>>, greater<>> pq;
set<pair<int,int>> seen;
pq.emplace(a[0] + b[0], 0, 0);
seen.insert({0, 0});
vector<vector<int>> ans;
while (k-- > 0 && !pq.empty()) {
auto [s, i, j] = pq.top(); pq.pop();
ans.push_back({a[i], b[j]});
if (i + 1 < (int)a.size() && !seen.count({i + 1, j})) {
pq.emplace(a[i + 1] + b[j], i + 1, j);
seen.insert({i + 1, j});
}
if (j + 1 < (int)b.size() && !seen.count({i, j + 1})) {
pq.emplace(a[i] + b[j + 1], i, j + 1);
seen.insert({i, j + 1});
}
}
return ans;
}
};

Editorial#

The k-pair grid problem is equivalent to a k-way merge where each “list” is a row of pair sums (row i is a[i] + b[0..n-1] ascending). Starting from (0,0) and expanding cardinally explores the grid in non-decreasing order via the heap; the visited set prevents duplicate pushes.

Complexity#

  • Time: O(k log k).
  • Space: O(k).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.