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
function cntDisPairs ( arr , N , K ) { var cntPairs = 0 ; arr . sort ( ) ; var i = 0 ; var j = N - 1 ; while ( i < j ) { if ( arr [ i ] + arr [ j ] == K ) { while ( i < j && arr [ i ] == arr [ i + 1 ] ) { i ++ ; } while ( i < j && arr [ j ] == arr [ j - 1 ] ) { j -- ; } cntPairs += 1 ; i ++ ; j -- ; } else if ( arr [ i ] + arr [ j ] < K ) { i ++ ; } else { j -- ; } } return cntPairs ; } var arr = [ 5 , 6 , 5 , 7 , 7 , 8 ] ; var N = arr . length ; var K = 13 ; document . write ( cntDisPairs ( arr , N , K ) ) ;