problem no 71: 2 sorted arrays are given ,count the number of pairs whose sum is equal to x.

 problem:

Given two sorted arrays(arr1[] and arr2[]) of size M and N of distinct elements. Given a value Sum. The problem is to count all pairs from both arrays whose sum is equal to Sum.
Note: The pair has an element from each array.


Example 1:

Input:
M=4, N=4 , Sum = 10
arr1[] = {1, 3, 5, 7}
arr2[] = {2, 3, 5, 8} 
Output: 2
Explanation: The pairs are: (5, 5) and (7, 3).  

 

Example 2:

Input:
N=4, M=4, sum=5 
arr1[] = {1, 2, 3, 4}
arr2[] = {5, 6, 7, 8}
Output: 0

 

Your Task:
Since, this is a function problem. You don't need to take any input, as it is already accomplished by the driver code. You just need to complete the function countPairs() that takes array arr1, array arr2, integer M, integer N and integer x as parameters and return the count of all pairs from both arrays whose sum is equal to x.


code:

    int countPairs(int arr1[], int arr2[],  int m, int n, int x) 

    { 

        int count=0;

       

       unordered_set<int> s;

       for(int i=0;i<m;i++)

       {

           s.insert(arr1[i]);

           

           

       }

       

       for(int i=0;i<n;i++)

       {

           if(s.find(x-arr2[i])!=s.end())

           {

               count=count+1;

           }

           

       }

       

       

       return count;

       

       

       

       

        

    } 

Comments

Popular posts from this blog

problem 3: given two integers N and M. The problem is to find the number closest to N and divisible by M. If there are more than one such number, then output the one having maximum absolute value.

problem no 7:Given two numbers A and B, find Kth digit from right of AB.

Problem no 16: count the number of squares below N.