Print all triplets with given sum | function to print triplets with given sum ; Find all pairs with sum equals to " sum - arr [ i ] " ; Driver code
function findTriplets ( arr , n , sum ) { for ( let i = 0 ; i < n - 1 ; i ++ ) { let s = new Set ( ) ; for ( let j = i + 1 ; j < n ; j ++ ) { let x = sum - ( arr [ i ] + arr [ j ] ) ; if ( s . has ( x ) ) document . write ( x + " " + arr [ i ] + " " + arr [ j ] + " " ) ; else s . add ( arr [ j ] ) ; } } } let arr = [ 0 , - 1 , 2 , - 3 , 1 ] ; let sum = - 2 ; let n = arr . length ; findTriplets ( arr , n , sum ) ;