Problem no 18(array):count the number of pairs in array whose sum is equal to the given number.

 

Count pairs with given sum
Easy

Given an array of N integers, and an integer K, find the number of pairs of elements in the array whose sum is equal to K.


Example 1:

Input:
N = 4, K = 6
arr[] = {1, 5, 7, 1}
Output: 2
Explanation: 
arr[0] + arr[1] = 1 + 5 = 6 
and arr[1] + arr[3] = 5 + 1 = 6.

 

 

ANSWER:

 int getPairsCount(int arr[], int n, int k) {
        int c=0;
        unordered_map<int,int> m;
        for(int i=0;i<n;i++)
        {
            int x=k-arr[i];
            if(m[x]==0)
            {
                m[arr[i]]=m[arr[i]]+1;
            }
            else
            {
                c=c+m[x];
                m[arr[i]]=m[arr[i]]+1;
            }
        }
       
        return c;
       
       
    }

 

 

 

Comments

Popular posts from this blog

convert the integer number to its binary representation.

Tcs assessment problem: museum problem.