Find K Pairs with Smallest Sums in C++

C++Server Side ProgrammingProgramming

Suppose we have two sorted arrays A1 and A2, and another value k. We have to define a pair (u, v) which is consists of one element from A1 and another element from A2. We have to find the k pairs like [(u1, v1), (u2, v2),…, (uk, vk)]. So if A1 = [1, 7, 11] and A2 = [2, 4, 6], and k = 3, then output will be [(1, 2), (1, 4), (1, 6)]

To solve this, we will follow these steps −

  • Define one data type, that will take two values a and b, and index.
  • create one priority queue, that will take key of type data and list of data as value.
  • n := size of A1, m := size of A2
  • if n is 0 or m is 0, then return
  • create one matrix called ret
  • for i in range 0 to n – 1
    • insert (A1[i], A2[0], 0) as data into queue
  • while queue is not empty, and k is not 0, then
    • curr := top of queue, delete queue element
    • insert first_val of curr, second_val of curr into ret
    • if index of curr + 1 < m, then
      • insert data with (first_val of curr, A2[index of curr + 1], index of curr + 1), into queue
    • decrease k by 1
  • return ret

Let us see the following implementation to get better understanding −

Example

 Live Demo

#include <bits/stdc++.h>
#include <stack>
using namespace std;
struct Data{
   int firstVal, secondVal, idx;
   Data(int a, int b, int c){
      firstVal = a;
      secondVal = b;
      idx = c;
   }
};
struct Comparator{
   bool operator()(Data a, Data b){
      return !(a.firstVal + a.secondVal < b.firstVal + b.secondVal);
   }
};
class Solution {
   public:
   vector<vector<int>> kSmallestPairs(vector<int>& nums1, vector<int>& nums2, int k) {
      priority_queue <Data, vector <Data>, Comparator> pq;
      int n = nums1.size();
      int m = nums2.size();
      if(!n || !m)return {};
      vector < vector <int> > ret;
      for(int i = 0; i < n; i++){
         pq.push(Data(nums1[i], nums2[0], 0));
      }
      while(!pq.empty() && k--){
         Data curr = pq.top();
         pq.pop();
         ret.push_back({curr.firstVal, curr.secondVal});
         if(curr.idx + 1 < m){
            pq.push(Data(curr.firstVal, nums2[curr.idx + 1], curr.idx + 1));
         }
      }
      return ret;
   }
};
void print(vector <int> const &arr) {
   cout<<"[";
   for(int i=0; i < arr.size(); i++)
      std::cout << arr.at(i) <<",";
   cout<<"]";
}
int main() {
   vector<int> nums1{1,7,11};
   vector<int> nums2{2,4,6};
   int k = 3;
   Solution ob1;
   vector<vector<int>> numsRet;
   numsRet = ob1.kSmallestPairs(nums1, nums2, k);
   cout<<"[";
   for (vector<int> x : numsRet) {
      print(x);
      cout<<",";
   }
   cout<<"]"<<endl;
   return 0;
}

Input

[1,7,11]
[2,4,6]
3
vector<int> nums1{1,7,11};
vector<int> nums2{2,4,6};
int k = 3;
Solution ob1;
vector<vector<int>> numsRet;
numsRet = ob1.kSmallestPairs(nums1, nums2, k);

Output

[[1,2,],[1,4,],[1,6,],]
raja
Published on 29-Apr-2020 14:14:08
Advertisements