27. Find K Smallest Sum Pairs
β GFG solution to Find K Smallest Sum Pairs problem: efficiently find k pairs with smallest sums from two sorted arrays using optimized heap approach. π
The problem can be found at the following link: π Question Link
π§© Problem Description
You are given two integer arrays arr1[] and arr2[] sorted in ascending order and an integer k. Your task is to find k pairs with the smallest sums, such that one element of each pair belongs to arr1[] and the other belongs to arr2[].
Return the list of these k pairs, where each pair is represented as [arr1[i], arr2[j]].
π Examples
Example 1
Input: arr1[] = [1, 7, 11], arr2[] = [2, 4, 6], k = 3
Output: true
Explanation: All possible combinations of elements from the two arrays are:
[1, 2], [1, 4], [1, 6], [7, 2], [7, 4], [7, 6], [11, 2], [11, 4], [11, 6].
Among these, the three pairs with the minimum sums are [1, 2], [1, 4], [1, 6].Example 2
Input: arr1[] = [1, 3], arr2[] = [2, 4] k = 2
Output: true
Explanation: All possible combinations are [1, 2], [1, 4], [3, 2], [3, 4].
Among these, the two pairs with the minimum sums are [1, 2], [3, 2].π Constraints
$1 \le \text{arr1.size()}, \text{arr2.size()} \le 5 \times 10^4$
$1 \le \text{arr1}[i], \text{arr2}[j] \le 10^9$
$1 \le k \le 10^3$
β
My Approach
The optimal approach uses a Min-Heap (Priority Queue) with an intelligent initialization strategy to efficiently find k smallest sum pairs:
Optimized Row-by-Row Heap Approach
Initialize Min-Heap:
Start by pushing the first element of each row in
arr1[]paired witharr2[0]into the min-heap.Only push
min(arr1.size(), k)initial pairs to optimize space.Each heap entry stores:
{sum, index_i, index_j}.
Extract Minimum Pairs:
Pop the top element (smallest sum) from the heap.
Add the corresponding pair
[arr1[i], arr2[j]]to the result.
Expand Window:
After extracting pair at indices
(i, j), push the next pair from the same row:(i, j+1).This ensures we only explore necessary pairs in sorted order.
Repeat Until k Pairs:
Continue extracting and expanding until we have collected
kpairs or heap becomes empty.
Key Optimization:
By initializing only the first column and expanding row-wise, we avoid exploring all
n*mpairs.The sorted property ensures we always get the next smallest sum.
π Time and Auxiliary Space Complexity
Expected Time Complexity: O(k*log(min(k,n))), where n is the size of arr1. We perform at most k heap operations, and the heap size is bounded by min(k, n) since we only initialize that many rows. Each heap operation takes O(log(heap_size)) time.
Expected Auxiliary Space Complexity: O(min(k,n)), as the heap stores at most min(k, n) elements at any time. This is significantly better than storing all n*m pairs.
π§βπ» Code (C++)
class Solution {
public:
vector<vector<int>> kSmallestPair(vector<int> &arr1, vector<int> &arr2, int k) {
vector<vector<int>> res;
priority_queue<pair<int,pair<int,int>>, vector<pair<int,pair<int,int>>>, greater<>> pq;
for(int i = 0; i < min((int)arr1.size(), k); i++) pq.push({arr1[i] + arr2[0], {i, 0}});
while(k-- && !pq.empty()) {
auto [sum, idx] = pq.top(); pq.pop();
auto [i, j] = idx;
res.push_back({arr1[i], arr2[j]});
if(j + 1 < arr2.size()) pq.push({arr1[i] + arr2[j + 1], {i, j + 1}});
}
return res;
}
};β Code (Java)
class Solution {
public ArrayList<ArrayList<Integer>> kSmallestPair(int[] arr1, int[] arr2, int k) {
ArrayList<ArrayList<Integer>> res = new ArrayList<>();
PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> a[0] - b[0]);
for(int i = 0; i < Math.min(arr1.length, k); i++) pq.offer(new int[]{arr1[i] + arr2[0], i, 0});
while(k-- > 0 && !pq.isEmpty()) {
int[] cur = pq.poll();
int i = cur[1], j = cur[2];
ArrayList<Integer> pair = new ArrayList<>();
pair.add(arr1[i]); pair.add(arr2[j]);
res.add(pair);
if(j + 1 < arr2.length) pq.offer(new int[]{arr1[i] + arr2[j + 1], i, j + 1});
}
return res;
}
}π Code (Python)
class Solution:
def kSmallestPair(self, arr1, arr2, k):
res = []
pq = [(arr1[i] + arr2[0], i, 0) for i in range(min(len(arr1), k))]
heapq.heapify(pq)
while k and pq:
s, i, j = heapq.heappop(pq)
res.append([arr1[i], arr2[j]])
if j + 1 < len(arr2): heapq.heappush(pq, (arr1[i] + arr2[j + 1], i, j + 1))
k -= 1
return resπ§ Contribution and Support
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: π¬ Any Questions?. Let's make this learning journey more collaborative!
β If you find this helpful, please give this repository a star! β
πVisitor Count
Last updated