Count pairs with given sum | C ++ implementation of simple method to find count of pairs with given sum . ; Returns number of pairs in arr [ 0. . n - 1 ] with sum equal to ' sum ' ; Store counts of all elements in map m ; initializing value to 0 , if key not found ; iterate through each element and increment the count ( Notice that every pair is counted twice ) ; if ( arr [ i ] , arr [ i ] ) pair satisfies the condition , then we need to ensure that the count is decreased by one such that the ( arr [ i ] , arr [ i ] ) pair is not considered ; return the half of twice_count ; Driver function to test the above function
#include <bits/stdc++.h> NEW_LINE using namespace std ; int getPairsCount ( int arr [ ] , int n , int sum ) { unordered_map < int , int > m ; for ( int i = 0 ; i < n ; i ++ ) m [ arr [ i ] ] ++ ; int twice_count = 0 ; for ( int i = 0 ; i < n ; i ++ ) { twice_count += m [ sum - arr [ i ] ] ; if ( sum - arr [ i ] == arr [ i ] ) twice_count -- ; } return twice_count / 2 ; } int main ( ) { int arr [ ] = { 1 , 5 , 7 , -1 , 5 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int sum = 6 ; cout << " Count ▁ of ▁ pairs ▁ is ▁ " << getPairsCount ( arr , n , sum ) ; return 0 ; }