Count distinct pairs with given sum | Java 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
import java . util . * ; class GFG { static int cntDisPairs ( int arr [ ] , int N , int K ) { int cntPairs = 0 ; HashMap < Integer , Integer > cntFre = new HashMap < Integer , Integer > ( ) ; for ( int i = 0 ; i < N ; i ++ ) { if ( cntFre . containsKey ( arr [ i ] ) ) cntFre . put ( arr [ i ] , cntFre . get ( arr [ i ] ) + 1 ) ; else cntFre . put ( arr [ i ] , 1 ) ; } for ( Map . Entry < Integer , Integer > it : cntFre . entrySet ( ) ) { int i = it . getKey ( ) ; if ( 2 * i == K ) { if ( cntFre . get ( i ) > 1 ) cntPairs += 2 ; } else { if ( cntFre . containsKey ( K - i ) ) { cntPairs += 1 ; } } } cntPairs = cntPairs / 2 ; return cntPairs ; } public static void main ( String [ ] args ) { int arr [ ] = { 5 , 6 , 5 , 7 , 7 , 8 } ; int N = arr . length ; int K = 13 ; System . out . print ( cntDisPairs ( arr , N , K ) ) ; } }