Find four elements that sum to a given value | Set 2 | The function finds four elements with given summ X ; Store summs of all pairs in a hash table ; Traverse through all pairs and search for X - ( current pair summ ) . ; If X - summ 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
def findFourElements ( arr , n , X ) : NEW_LINE INDENT mp = { } NEW_LINE for i in range ( n - 1 ) : NEW_LINE INDENT for j in range ( i + 1 , n ) : NEW_LINE INDENT mp [ arr [ i ] + arr [ j ] ] = [ i , j ] NEW_LINE DEDENT DEDENT for i in range ( n - 1 ) : NEW_LINE INDENT for j in range ( i + 1 , n ) : NEW_LINE INDENT summ = arr [ i ] + arr [ j ] NEW_LINE if ( X - summ ) in mp : NEW_LINE INDENT p = mp [ X - summ ] NEW_LINE if ( p [ 0 ] != i and p [ 0 ] != j and p [ 1 ] != i and p [ 1 ] != j ) : NEW_LINE INDENT print ( arr [ i ] , " , ▁ " , arr [ j ] , " , ▁ " , arr [ p [ 0 ] ] , " , ▁ " , arr [ p [ 1 ] ] , sep = " " ) NEW_LINE return NEW_LINE DEDENT DEDENT DEDENT DEDENT DEDENT arr = [ 10 , 20 , 30 , 40 , 1 , 2 ] NEW_LINE n = len ( arr ) NEW_LINE X = 91 NEW_LINE findFourElements ( arr , n , X ) NEW_LINE