Find four elements that sum to a given value | Set 2 | The function finds four elements with given sum X ; Store sums of all pairs in a hash table ; Traverse through all pairs and search for X - ( current pair sum ) . ; If X - sum is present in hash table , ; Making sure that all elements are distinct array elements and an element is not considered more than once . ; Driver Code ; Function call
function findFourElements ( arr , n , X ) { let mp = new Map ( ) ; for ( let i = 0 ; i < n - 1 ; i ++ ) for ( let j = i + 1 ; j < n ; j ++ ) mp . set ( arr [ i ] + arr [ j ] , [ i , j ] ) ; for ( let i = 0 ; i < n - 1 ; i ++ ) { for ( let j = i + 1 ; j < n ; j ++ ) { let sum = arr [ i ] + arr [ j ] ; if ( mp . has ( X - sum ) ) { let p = mp . get ( X - sum ) ; if ( p [ 0 ] != i && p [ 0 ] != j && p [ 1 ] != i && p [ 1 ] != j ) { document . write ( arr [ i ] + " " + arr [ j ] + " " + arr [ p [ 0 ] ] + " " + arr [ p [ 1 ] ] ) ; return ; } } } } } let arr = [ 10 , 20 , 30 , 40 , 1 , 2 ] ; let n = arr . length ; let X = 91 ; findFourElements ( arr , n , X ) ;