Count pairs with given sum | Practice | GeeksforGeeks

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.


Example 2:
Input:
N = 4, K = 2
arr[] = {1, 1, 1, 1}
Output: 6
Explanation: 
Each 1 will produce sum 2 with any 1.

Your Task:
You don't need to read input or print anything. Your task is to complete the function getPairsCount() which takes arr[], n and k as input parameters and returns the number of pairs that have sum K.

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

Constraints:
1 <= N <= 105
1 <= K <= 108
1 <= Arr[i] <= 106
 
0
satan3 days ago
Easiest C++ solution
int getPairsCount(int a[], int n, int k) {       // code here       unordered_map<int,int> m;       int c=0;       for(int i=0;i<n;i++)       {           c+=m[k-a[i]];           m[a[i]]++;       }       return c;   }
0
ohyeahpiet1 week ago
class Solution{   public:   int getPairsCount(int arr[], int n, int k) {       unordered_map<int,int> m;       int ans=0;       for(int i = 0 ; i < n ; i++){           int val = k - arr[i];           if(m[val]){               ans += m[val];           }           m[arr[i]]++;       }       return ans;   }};
0
tanishabhadanianve2 weeks ago
// JAVA SOLUTION
 
int getPairsCount(int[] arr, int n, int k) {              HashMap<Integer,Integer> map = new HashMap<>();       int count=0;              for(int i=0;i<n;i++)       {           if(map.containsKey(k-arr[i])) {               count += map.get(k-arr[i]);           }                      if(!map.containsKey(arr[i]))               map.put(arr[i],1);                              else               map.put(arr[i],map.get(arr[i])+1);       }              return count;   }
+1
bijeshkumarch2 weeks ago
#Python
dct=dict()       for i in arr:           dct[i]=0       for i in arr:           dct[i]+=1       cnt=0       for i in dct.keys():           if 2*i==k and dct[i]>1:               cnt+=(dct[i]*(dct[i]-1))//2               dct[i]=0           else:               if k-i in dct.keys():                   if i==k-i:                       continue                   cnt+=(dct[i]*dct[k-i])                   dct[i],dct[k-i]=0,0       return cnt
0
kousikbarik20002 weeks ago
def findPairs(arr,target):    for i in range(len(arr)):        for j in range(i+1,len(arr)):            if arr[i] == arr[j]:                continue            elif arr[i] + arr[j] == target:                    print(i,j)arr = [1,5,7,1]findPairs(arr,6)
0
rajivkumawat280120022 weeks ago
simple and easy solution in c++........i solve it after 31 attempts...............
 
 int getPairsCount(int arr[], int n, int k) {       // code here       sort(arr,arr+n);int flag=0;int count=0;int low=0;int high=n-1;int temp;
while(low<high){   if(arr[low]+arr[high]==k)   {    flag=1;       count++;       temp=high;      while(low<high-1)     {       if(arr[low]+arr[high-1]==k)       {           count++;       }       high--;     }     high=temp;     low++;   }
   else if(arr[low]+arr[high]>k)   {       high--;   }
   else   low++;
}
if(flag==0){ return {0};}
else{   return count;}
   }
+1
rajivkumawat28012002
This comment was deleted.
0
gautambaddy2 weeks ago
//optimize the solution
class Solution{   public:   int getPairsCount(int arr[], int n, int k) {       // codint k=0;   int l=0;   int i=0;   while( i<n){       for(int j=i+1;j<n;j++){           int sum=0;           if (arr[i]<k){               sum=arr[i]+arr[j];               if (sum==k){                   l+=1;                                  }                          }              }i++;   }   return l;      }}; 
+1
deepakprakashjyotisahu2 weeks ago
      //1.HashMap       int c=0;       HashMap<Integer,Integer>map=new HashMap<>();       for(int i=0;i<arr.length;i++){           if(map.containsKey(k-arr[i])){               c=c+map.get(k-arr[i]);           }           map.put(arr[i],map.getOrDefault(arr[i],0)+1);       }       return c;
+2
anishmeena0013 weeks ago
class Solution{   public:   int getPairsCount(int arr[], int n, int k) {       // code here       int ans=0;      unordered_map<int,int> m;      for(int i=0;i<n;i++)      {          m[arr[i]]++;      }          for(int i=0;i<n;i++)          {          ans+=m[k-arr[i]];          if(k-arr[i]==arr[i])          {              ans--;          }                }            return ans/2;   }};
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.