8

Given 5 arrays of size n: a, b, c, d, e. How many (i, j, k, g, h) are there such that

a(i) + b(j) + c(k) + d(g) + e(h) = 0 ?

Can this problem be solved with complexity better than O(n^2 + n^3) (using hash map) ?

Xeing
  • 314
  • 3
  • 10
  • 2
    Assuming you're referring to integers and that the distribution of positive/negative numbers is equal (across all 5 arrays) - I don't see how it can be done in better time complexity than `O(n^3)` – Nir Alfasi Aug 23 '14 at 06:54
  • Do the arrays contain only unique numbers or they can contain duplicates ? – ROMANIA_engineer Aug 23 '14 at 06:56
  • They can contain dublicates – Xeing Aug 23 '14 at 06:58
  • @curiosu duplicates within an array can be removed because we may need at most one of them. – Abhishek Bansal Aug 23 '14 at 07:08
  • I suppose that if he has a = [-2, -2] b = [-1, -1] c = [0, 0] d = [1, 1] and e = [2, 2] the answer for "how many" will be 32, not 1. ( 0-0-0-0-0, ..., 0-0-0-0-1 ,..., 1-1-1-1-1 ) – ROMANIA_engineer Aug 23 '14 at 07:16
  • @curiosu Yes, but you can easily remove them from your search. – Abhishek Bansal Aug 23 '14 at 07:19
  • @alfasin may be you are right, cs.stackexchange.com/questions/2973/generalised-3sum-k-sum-problem – Xeing Aug 23 '14 at 11:35
  • "If you can't solve a problem, then there is an easier problem you can solve: find it." —Polya. It might help to think about the problem with only two or three arrays. – Colonel Panic Aug 26 '14 at 10:27
  • Note that Wikipedia lists "Is there an algorithm to solve the 3SUM problem faster than O(n**2) time?" among 'unsolved problems in computer science'. https://en.wikipedia.org/wiki/3SUM – Colonel Panic Aug 26 '14 at 10:31

1 Answers1

3

If the arrays contain integers of limited size (i.e. in range -u to u) then you can solve this in O(n+ulogu) time by using the fast Fourier transform to convolve the histograms of each collection together.

For example, the set a=[-1,2,2,2,2,3] would be represented by a histogram with values:

ha[-1] = 1
ha[2]  = 4
ha[3]  = 1

After convolving all the histograms together with the FFT, the resulting histogram will contain entries where the value for each bin tells you the number of ways of combining the numbers to get each possible total. To find the answer to your question with a total of 0, all you need to do is read the value of the histogram for bin 0.

Peter de Rivaz
  • 33,126
  • 4
  • 46
  • 75