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++:
- #include<iostream>
- #include<bits/stdc++.h>
- using namespace std;
- int main()
- {
- int t;
- cin>>t;
- while(t--)
- {
- int n,m,x;
- cin>>n>>m>>x;
- int a[n],b[m];
- for(int i=0;i<n;i++)
- {
- cin>>a[i];
- }
- sort(a,a+n);
- map<int,int> s;
- for(int i=0;i<m;i++)
- {
- cin>>b[i];
- s[b[i]]++;
- }
- int c=0;
- for(int i=0;i<n;i++)
- {
- if(s.find(x-a[i])!=s.end())
- {
- if(c!=0) cout<<","<<" ";
- cout<<a[i]<<" "<<x-a[i];
- c++;
- }
- }
- if(c==0) cout<<-1;
- cout<<endl;
- }
- return 0;
- }
Here is the Video: