text: Count pairs with given sum | Set 2 | Function to return the count of pairs from arr [ ] with the given sum ; To store the count of pairs ; Sort the given array ; Take two pointers ; If sum is greater ; If sum is lesser ; If sum is equal ; Find the frequency of arr [ i ] ; Find the frequency of arr [ j ] ; If arr [ i ] and arr [ j ] are same then remove the extra number counted ; Return the required answer ; Driver code
code: function pairs_count ( arr , n , sum ) { let ans = 0 ; arr . sort ( ) ; let i = 0 , j = n - 1 ; while ( i < j ) { if ( arr [ i ] + arr [ j ] < sum ) i ++ ; else if ( arr [ i ] + arr [ j ] > sum ) j -- ; else { let x = arr [ i ] , xx = i ; while ( i < j && arr [ i ] == x ) i ++ ; let y = arr [ j ] , yy = j ; while ( j >= i && arr [ j ] == y ) j -- ; if ( x == y ) { let temp = i - xx + yy - j - 1 ; ans += ( temp * ( temp + 1 ) ) / 2 ; } else ans += ( i - xx ) * ( yy - j ) ; } } return ans ; } let arr = [ 1 , 5 , 7 , 5 , - 1 ] ; let n = arr . length ; let sum = 6 ; document . write ( pairs_count ( arr , n , sum ) ) ;