text: Count distinct pairs with given sum | C ++ program to implement the above approach ; Function to count distinct pairs in array whose sum equal to K ; Stores count of distinct pairs whose sum equal to K ; Store frequency of each distinct element of the array ; Update frequency of arr [ i ] ; Traverse the map ; Stores key value of the map ; If i is the half of K ; If frequency of i greater than 1 ; Update cntPairs ; Update cntPairs ; Driver Code
code: #include <bits/stdc++.h> NEW_LINE using namespace std ; int cntDisPairs ( int arr [ ] , int N , int K ) { int cntPairs = 0 ; unordered_map < int , int > cntFre ; for ( int i = 0 ; i < N ; i ++ ) { cntFre [ arr [ i ] ] ++ ; } for ( auto it : cntFre ) { int i = it . first ; if ( 2 * i == K ) { if ( cntFre [ i ] > 1 ) cntPairs += 2 ; } else { if ( cntFre [ K - i ] ) { cntPairs += 1 ; } } } cntPairs = cntPairs / 2 ; return cntPairs ; } int main ( ) { int arr [ ] = { 5 , 6 , 5 , 7 , 7 , 8 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int K = 13 ; cout << cntDisPairs ( arr , N , K ) ; }