Count distinct pairs with given sum | 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
def cntDisPairs ( arr , N , K ) : NEW_LINE INDENT cntPairs = 0 NEW_LINE cntFre = { } NEW_LINE for i in arr : NEW_LINE INDENT if i in cntFre : NEW_LINE INDENT cntFre [ i ] += 1 NEW_LINE DEDENT else : NEW_LINE INDENT cntFre [ i ] = 1 NEW_LINE DEDENT DEDENT for key , value in cntFre . items ( ) : NEW_LINE INDENT i = key NEW_LINE if ( 2 * i == K ) : NEW_LINE INDENT if ( cntFre [ i ] > 1 ) : NEW_LINE INDENT cntPairs += 2 NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT if ( cntFre [ K - i ] ) : NEW_LINE INDENT cntPairs += 1 NEW_LINE DEDENT DEDENT DEDENT cntPairs = cntPairs / 2 NEW_LINE return cntPairs NEW_LINE DEDENT arr = [ 5 , 6 , 5 , 7 , 7 , 8 ] NEW_LINE N = len ( arr ) NEW_LINE K = 13 NEW_LINE print ( int ( cntDisPairs ( arr , N , K ) ) ) NEW_LINE