Find four elements that sum to a given value | Set 2 | Function to find 4 elements that add up to given sum ; Iterate from 0 to temp . length ; Iterate from 0 to length of arr ; Iterate from i + 1 to length of arr ; Store curr_sum = arr [ i ] + arr [ j ] ; Check if X - curr_sum if present in map ; Store pair having map value X - curr_sum ; Print the output ; Function for two Sum ; Driver code ; Function call
def fourSum ( X , arr , Map , N ) : NEW_LINE INDENT temp = [ 0 for i in range ( N ) ] NEW_LINE for i in range ( N - 1 ) : NEW_LINE INDENT for j in range ( i + 1 , N ) : NEW_LINE INDENT curr_sum = arr [ i ] + arr [ j ] NEW_LINE if ( X - curr_sum ) in Map : NEW_LINE INDENT p = Map [ X - curr_sum ] NEW_LINE if ( p [ 0 ] != i and p [ 1 ] != i and p [ 0 ] != j and p [ 1 ] != j and temp [ p [ 0 ] ] == 0 and temp [ p [ 1 ] ] == 0 and temp [ i ] == 0 and temp [ j ] == 0 ) : NEW_LINE INDENT print ( arr [ i ] , " , " , arr [ j ] , " , " , arr [ p [ 0 ] ] , " , " , arr [ p [ 1 ] ] , sep = " " ) NEW_LINE temp [ p [ 1 ] ] = 1 NEW_LINE temp [ i ] = 1 NEW_LINE temp [ j ] = 1 NEW_LINE break NEW_LINE DEDENT DEDENT DEDENT DEDENT DEDENT def twoSum ( nums , N ) : NEW_LINE INDENT Map = { } NEW_LINE for i in range ( N - 1 ) : NEW_LINE INDENT for j in range ( i + 1 , N ) : NEW_LINE INDENT Map [ nums [ i ] + nums [ j ] ] = [ ] NEW_LINE Map [ nums [ i ] + nums [ j ] ] . append ( i ) NEW_LINE Map [ nums [ i ] + nums [ j ] ] . append ( j ) NEW_LINE DEDENT DEDENT return Map NEW_LINE DEDENT arr = [ 10 , 20 , 30 , 40 , 1 , 2 ] NEW_LINE n = len ( arr ) NEW_LINE X = 91 NEW_LINE Map = twoSum ( arr , n ) NEW_LINE fourSum ( X , arr , Map , n ) NEW_LINE