Find all pairs with a given sum | Practice | GeeksforGeeks

Given two unsorted arrays A of size N and B of size M of distinct elements, the task is to find all pairs from both arrays whose sum is equal to X.
 
Example 1:
Input:
A[] = {1, 2, 4, 5, 7}
B[] = {5, 6, 3, 4, 8} 
X = 9 
Output: 
1 8
4 5 
5 4
Explanation:
(1, 8), (4, 5), (5, 4) are the
pairs which sum to 9.

Input:
A[] = {-1, -2, 4, -6, 5, 7}
B[] = {6, 3, 4, 0} 
X = 8 
Output:
4 4 
5 3


Your Task:  
You don't need to read input or print anything. Your task is to complete the function allPairs() which takes the array A[], B[], its size N and M respectively and an integer X as inputs and returns the sorted vector pair values of all the pairs u,v where u belongs to array A and v belongs to array B. If no such pair exist return empty vector pair.
Note : All pairs should be printed in increasing order of u. For eg. for two pairs (u1,v1) and (u2,v2), if u1<u2 then
(u1,v1) should be printed first else second.

Expected Time Complexity: O(NLog(N))
Expected Auxiliary Space: O(N)

Constraints:
1 ≤ N, M ≤ 106
-106 ≤ X, A[i], B[i] ≤ 106
+1
somya95singh1 week ago
class Solution {   public pair[] allPairs( long A[], long B[], long N, long M, long X) {       ArrayList<pair> ans = new ArrayList<pair>();       Arrays.sort(A);       Arrays.sort(B);              Set<Long> s = new HashSet<Long>();       for(int i=0;i<M;i++){           s.add(B[i]);       }       for(int i=0;i<N;i++){           long diff = X-A[i];           if(s.contains(diff)){               ans.add(new pair(A[i] , diff));           }       }       int n = ans.size();       pair p[] = new pair[n];       for(int i=0;i<n;i++){           p[i] = new pair(ans.get(i).first , ans.get(i).second);       }       return p;
    }
}
+1
nikipyati2 weeks ago
class Solution:
    def allPairs(self, A, B, N, M, X):
        l=[]
        for i in range(N):
            s=0
            for j in range(M):
                if A[i]+B[j]==X:
                    l.append((A[i],B[j]))
        l.sort()
        return l
+1
lindan1232 weeks ago
vector<pair<int,int>> allPairs(int A[], int B[], int N, int M, int X)
    {
        vector<pair<int,int>> vec;
        set<int> s;
        for(int i=0;i<M;i++)
        {
            s.insert(B[i]);
        }
        
        for(int i=0;i<N;i++)
        {
            int temp = X-A[i];
            if(s.find(temp)!=s.end())
            {
                vec.push_back({A[i],temp});
            }
        }
        sort(vec.begin(),vec.end());
        return vec;
    }
Time Taken : 0.06sec
Cpp
0
subhamsen13 weeks ago
Python solution
 
def allPairs(A, B, N,M, X):    # Your code goes here    """    Traverse list 1 and then make a dictionary of required number X-I    if the required number found in dictionary get the key and this i    a_dic={key:None for key in A }    b_dic= {key:None for key in B }    res=[]    for element in a_dic:        required_number=X-element        if required_number in b_dic:            res.append((element,required_number))    # output has to be sorted    res.sort()    return res 
0
tupesanket19993 weeks ago
vector<pair<int,int>> allPairs(int A[], int B[], int N, int M, int X){
       vector<pair<int,int>>vec;
       unordered_set<int>st(B,B+M);
       for(int i=0;i< N;i++)if(st.find(X-A[i])!=st.end())vec.push_back({A[i],X-A[i]});
       sort(vec.begin(),vec.end());
       return vec;
   }
0
madhukartemba4 weeks ago
JAVA SOLUTION:
class Solution
{
    public pair[] allPairs( long A[], long B[], long N, long M, long X)
    {
        ArrayList<pair> ans = new ArrayList<>();
        Arrays.sort(A);
        Arrays.sort(B);
        
        int low = 0, high = (int)M-1;
        
        while(low<N && high>=0)
        {
            long sum = A[low] + B[high];
            if(sum>X)
            {
                high--;
            }
            else if(sum<X)
            {
                low++;
            }
            else
            {
                ans.add(new pair(A[low], B[high]));
                high--;
                low++;
            }
        }
        
        int n = ans.size();
        
        pair p[] = new pair[n];
        
        for(int i=0; i<n; i++)
        {
            p[i] = new pair(ans.get(i).first, ans.get(i).second);
        }
        
        return p;
        
    }
}
0
pritamaber4 weeks ago
    
    vector<pair<int,int>> allPairs(int A[], int B[], int N, int M, int X)
    {
        // Your code goes here   
        vector<pair<int, int>> ans;
        
        unordered_set<int> s2(B, B+M);
        
        for(int i = 0; i<N; i++){
            if(s2.find(X-A[i]) != s2.end()){
                ans.push_back(make_pair(A[i], X-A[i]));
            }
        }
        sort(ans.begin(), ans.end());
        return ans;
    }
0
arpitjaiswal481 month ago
vector<pair<int,int>> allPairs(int A[], int B[], int N, int M, int X)
    {
        // Your code goes here 
        sort(A,A+N);
        vector<pair<int,int>> v;
        unordered_map<int,int> m;
        for(int i=0;i<M;i++){
            m[B[i]]++;
        }
        for(int i=0;i<N;i++){
            if(m.find(X-A[i]) != m.end()){
                v.push_back(make_pair(A[i],X-A[i]));
            }else{
                continue;
            }
        }
        return v;
    }
0
praveenkumar1391521 month ago
#User function Template for python3
class Solution:   def allPairs(self, A, B, N, M, X):       A.sort()       d=[]       s=set(B)       for i in A:           if X-i in s:               d.append((i,X-i))       return d        
0
ayushkumar54512 months ago
vector<pair<int,int>> allPairs(int A[], int B[], int N, int M, int X)   {       // Your code goes here     map<int,int>mp;     for(int i=0;i<N;i++){         mp[A[i]]++;     }     vector<pair<int,int>>v;     for(int i=0;i<M;i++){         if(mp.find(X-B[i])!=mp.end()){             v.push_back({X-B[i],B[i]});         }     }     sort(v.begin(),v.end());     return v;   }
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.