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 ; Sort the array ; Stores index of the left pointer ; Stores index of the right pointer ; Calculate count of distinct pairs whose sum equal to K ; If sum of current pair is equal to K ; Remove consecutive duplicate array elements ; Update i ; Remove consecutive duplicate array elements ; Update j ; Update cntPairs ; Update i ; Update j ; If sum of current pair less than K ; Update i ; Update j ; Driver Code
def cntDisPairs ( arr , N , K ) : NEW_LINE INDENT cntPairs = 0 NEW_LINE arr = sorted ( arr ) NEW_LINE i = 0 NEW_LINE j = N - 1 NEW_LINE while ( i < j ) : NEW_LINE INDENT if ( arr [ i ] + arr [ j ] == K ) : NEW_LINE INDENT while ( i < j and arr [ i ] == arr [ i + 1 ] ) : NEW_LINE INDENT i += 1 NEW_LINE DEDENT while ( i < j and arr [ j ] == arr [ j - 1 ] ) : NEW_LINE INDENT j -= 1 NEW_LINE DEDENT cntPairs += 1 NEW_LINE i += 1 NEW_LINE j -= 1 NEW_LINE DEDENT elif ( arr [ i ] + arr [ j ] < K ) : NEW_LINE INDENT i += 1 NEW_LINE DEDENT else : NEW_LINE INDENT j -= 1 NEW_LINE DEDENT DEDENT return cntPairs NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 5 , 6 , 5 , 7 , 7 , 8 ] NEW_LINE N = len ( arr ) NEW_LINE K = 13 NEW_LINE print ( cntDisPairs ( arr , N , K ) ) NEW_LINE DEDENT