Given two integer arrays arr1[] and arr2[] sorted in ascending order and an integer k. Find k pairs with smallest sums such that one element of a pair belongs to arr1[] and other element belongs to arr2[]
Examples:
Input : arr1[] = {1, 7, 11}
arr2[] = {2, 4, 6}
k = 3
Output : [1, 2],
[1, 4],
[1, 6]
Explanation: The first 3 pairs are returned
from the sequence [1, 2], [1, 4], [1, 6],
[7, 2], [7, 4], [11, 2], [7, 6], [11, 4],
[11, 6]
Method 1 (Simple)
- Find all pairs and store their sums. Time complexity of this step is O(n1 * n2) where n1 and n2 are sizes of input arrays.
- Then sort pairs according to sum. Time complexity of this step is O(n1 * n2 * log (n1 * n2))
Overall Time Complexity : O(n1 * n2 * log (n1 * n2))
Method 2 (Efficient):
We one by one find k smallest sum pairs, starting from least sum pair. The idea is to keep track of all elements of arr2[] which have been already considered for every element arr1[i1] so that in an iteration we only consider next element. For this purpose, we use an index array index2[] to track the indexes of next elements in the other array. It simply means that which element of second array to be added with the element of first array in each and every iteration. We increment value in index array for the element that forms next minimum value pair.
C++
#include<bits/stdc++.h>
using namespace std;
void kSmallestPair( int arr1[], int n1, int arr2[],
int n2, int k)
{
if (k > n1*n2)
{
cout << "k pairs don't exist" ;
return ;
}
int index2[n1];
memset (index2, 0, sizeof (index2));
while (k > 0)
{
int min_sum = INT_MAX;
int min_index = 0;
for ( int i1 = 0; i1 < n1; i1++)
{
if (index2[i1] < n2 &&
arr1[i1] + arr2[index2[i1]] < min_sum)
{
min_index = i1;
min_sum = arr1[i1] + arr2[index2[i1]];
}
}
cout << "(" << arr1[min_index] << ", "
<< arr2[index2[min_index]] << ") " ;
index2[min_index]++;
k--;
}
}
int main()
{
int arr1[] = {1, 3, 11};
int n1 = sizeof (arr1) / sizeof (arr1[0]);
int arr2[] = {2, 4, 8};
int n2 = sizeof (arr2) / sizeof (arr2[0]);
int k = 4;
kSmallestPair( arr1, n1, arr2, n2, k);
return 0;
}
|
Output(1, 2) (1, 4) (3, 2) (3, 4)
Time Complexity : O(k*n1), where n1 represents the size of the given array.
Auxiliary Space: O(n1), where n1 represents the size of the given array.
Method 3 : Using Sorting, Min heap, Map
Instead of brute forcing through all the possible sum combinations we should find a way to limit our search space to possible candidate sum combinations.
- Sort both arrays array A and array B.
- Create a min heap i.e priority_queue in C++ to store the sum combinations along with the indices of elements from both arrays A and B which make up the sum. Heap is ordered by the sum.
- Initialize the heap with the minimum possible sum combination i.e (A[0] + B[0]) and with the indices of elements from both arrays (0, 0). The tuple inside min heap will be (A[0] + B[0], 0, 0). Heap is ordered by first value i.e sum of both elements.
- Pop the heap to get the current smallest sum and along with the indices of the element that make up the sum. Let the tuple be (sum, i, j).
- Next insert (A[i + 1] + B[j], i + 1, j) and (A[i] + B[j + 1], i, j + 1) into the min heap but make sure that the pair of indices i.e (i + 1, j) and (i, j + 1) are not already present in the min heap.To check this we can use set in C++.
- Go back to 4 until K times.
C++
#include <bits/stdc++.h>
using namespace std;
void kSmallestPair(vector< int > A, vector< int > B, int K)
{
sort(A.begin(), A.end());
sort(B.begin(), B.end());
int n = A.size();
priority_queue<pair< int , pair< int , int > >,
vector<pair< int , pair< int , int > > >,
greater<pair< int , pair< int , int > > > >
pq;
set<pair< int , int > > my_set;
pq.push(make_pair(A[0] + B[0], make_pair(0, 0)));
my_set.insert(make_pair(0, 0));
int flag=1;
for ( int count = 0; count < K && flag; count++) {
pair< int , pair< int , int > > temp = pq.top();
pq.pop();
int i = temp.second.first;
int j = temp.second.second;
cout << "(" << A[i] << ", " << B[j] << ")"
<< endl;
flag=0;
if (i + 1 < A.size()) {
int sum = A[i + 1] + B[j];
pair< int , int > temp1 = make_pair(i + 1, j);
if (my_set.find(temp1) == my_set.end()) {
pq.push(make_pair(sum, temp1));
my_set.insert(temp1);
}
flag=1;
}
if (j + 1 < B.size()) {
int sum = A[i] + B[j + 1];
pair< int , int > temp1 = make_pair(i, j + 1);
if (my_set.find(temp1) == my_set.end()) {
pq.push(make_pair(sum, temp1));
my_set.insert(temp1);
}
flag=1;
}
}
}
int main()
{
vector< int > A = { 1 };
vector< int > B = { 2, 4, 5, 9 };
int K = 3;
kSmallestPair(A, B, K);
return 0;
}
|
Output(1, 2)
(1, 4)
(1, 5)
Time Complexity : O(n*logn) assuming k<=n.
Auxiliary Space: O(n), where n is the size of the given array.
Please refer complete article on Find k pairs with smallest sums in two arrays for more details!