Skip to main content

All pairs with a given Sum

Task: Given two unsorted arrays A and B with N and M distinct elements respectively, Find all pairs from both arrays whose sum is equal to X.

Example:
Input:
1
5 5 9
1 2 4 5 7
5 6 3 4 8
Output:
1 8, 4 5, 5 4

Here is the Code:
Program in C++:

  1. #include<iostream>
  2. #include<bits/stdc++.h>
  3. using namespace std;
  4. int main()
  5.  {
  6. int t;
  7. cin>>t;
  8. while(t--)
  9. {
  10.     int n,m,x;
  11.     cin>>n>>m>>x;
  12.     int a[n],b[m];
  13.     for(int i=0;i<n;i++)
  14.     {
  15.         cin>>a[i];
  16.     }
  17.     sort(a,a+n);
  18.     map<int,int> s;
  19.     for(int i=0;i<m;i++)
  20.     {
  21.         cin>>b[i];
  22.         s[b[i]]++;
  23.     }
  24.     int c=0;
  25.     for(int i=0;i<n;i++)
  26.     {
  27.         if(s.find(x-a[i])!=s.end())
  28.         {
  29.             if(c!=0) cout<<","<<" ";
  30.             cout<<a[i]<<" "<<x-a[i];
  31.             c++;
  32.         }
  33.     }
  34.     if(c==0) cout<<-1;
  35.     cout<<endl;
  36. }
  37. return 0;
  38. }


Here is the Video: