Count pairs with given sum | Python 3 implementation of simple method to find count of pairs with given sum . ; Returns number of pairs in arr [ 0. . n - 1 ] with sum equal to 'sum   ; Store counts of all elements in map m ; initializing value to 0 , if key not found ; Iterate through each element and increment the count ( Notice that every pair is counted twice ) ; if ( arr [ i ] , arr [ i ] ) pair satisfies the condition , then we need to ensure that the count is decreased by one such that the ( arr [ i ] , arr [ i ] ) pair is not considered ; return the half of twice_count ; Driver function
import sys NEW_LINE def getPairsCount ( arr , n , sum ) : NEW_LINE INDENT m = [ 0 ] * 1000 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT m [ arr [ i ] ] += 1 NEW_LINE DEDENT twice_count = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT twice_count += m [ sum - arr [ i ] ] NEW_LINE if ( sum - arr [ i ] == arr [ i ] ) : NEW_LINE INDENT twice_count -= 1 NEW_LINE DEDENT DEDENT return int ( twice_count / 2 ) NEW_LINE DEDENT arr = [ 1 , 5 , 7 , - 1 , 5 ] NEW_LINE n = len ( arr ) NEW_LINE sum = 6 NEW_LINE print ( " Count ▁ of ▁ pairs ▁ is " , getPairsCount ( arr , n , sum ) ) NEW_LINE