Print all 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 ; Traverse through all elements ; Search if a pair can be formed with arr [ i ] . ; Driver code
function printPairs ( arr , n , sum ) { var m = { } ; for ( var i = 0 ; i < n ; i ++ ) { var rem = sum - arr [ i ] ; if ( m . hasOwnProperty ( rem ) ) { var count = m [ rem ] ; for ( var j = 0 ; j < count ; j ++ ) { document . write ( " " + rem + " " + arr [ i ] + " " + " " ) ; } } if ( m . hasOwnProperty ( arr [ i ] ) ) { m [ arr [ i ] ] ++ ; } else { m [ arr [ i ] ] = 1 ; } } } var arr = [ 1 , 5 , 7 , - 1 , 5 ] ; var n = arr . length ; var sum = 6 ; printPairs ( arr , n , sum ) ;