Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Given 4 arrays, find number of quadruples having zero sum [closed]

  • Given 4 arrays that can contain positive and negative numbers.
  • find all possible sets with one number from each array (ie each set will contain 4 numbers ) such that sum of 4 numbers is zero.
like image 905
MoveFast Avatar asked Feb 22 '23 02:02

MoveFast


1 Answers

Adrian just hasn't thought far enough :-)

Loop through array 1 and 2 and add all sums to a map.

Now from the other 2 arrays find all combinations which add up to a number in the map which you got from array 1 and 2. It's pretty straight forward. Let me know if you need some pseudocode.

O(n^2) runtime

like image 81
Gunther Piez Avatar answered Feb 23 '23 16:02

Gunther Piez