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
def pairs_count ( arr , n , sum ) : NEW_LINE INDENT ans = 0 NEW_LINE arr = sorted ( arr ) NEW_LINE i , j = 0 , n - 1 NEW_LINE while ( i < j ) : NEW_LINE INDENT if ( arr [ i ] + arr [ j ] < sum ) : NEW_LINE INDENT i += 1 NEW_LINE DEDENT elif ( arr [ i ] + arr [ j ] > sum ) : NEW_LINE INDENT j -= 1 NEW_LINE DEDENT else : NEW_LINE INDENT x = arr [ i ] NEW_LINE xx = i NEW_LINE while ( i < j and arr [ i ] == x ) : NEW_LINE INDENT i += 1 NEW_LINE DEDENT y = arr [ j ] NEW_LINE yy = j NEW_LINE while ( j >= i and arr [ j ] == y ) : NEW_LINE INDENT j -= 1 NEW_LINE DEDENT if ( x == y ) : NEW_LINE INDENT temp = i - xx + yy - j - 1 NEW_LINE ans += ( temp * ( temp + 1 ) ) // 2 NEW_LINE DEDENT else : NEW_LINE INDENT ans += ( i - xx ) * ( yy - j ) NEW_LINE DEDENT DEDENT DEDENT return ans NEW_LINE DEDENT arr = [ 1 , 5 , 7 , 5 , - 1 ] NEW_LINE n = len ( arr ) NEW_LINE sum = 6 NEW_LINE print ( pairs_count ( arr , n , sum ) ) NEW_LINE