Quadratic algorithm for 4-SUM

Yes you can. Go over all pairs of numbers and store their sum(and also store which numbers give that sum). After that for each sum check if its negation is found among the sums you have. Using a hash you can reach quadratic complexity, using std::map, you will reach O(n^2*log(n)).

EDIT: to make sure no number is used more than once it will better to store indices instead of the actual numbers for each sum. Also as a given sum may be formed by more than one pair, you will have to use a hash multimap. Having in mind the numbers are different for a sum X = a1 + a2 the sum -X may be formed at most once using a1 and once using a2 so for a given sum X you will have to iterate over at most 3 pairs giving -X as sum. This is still constant.


There is also a O(N2) algorithm for this problem using O(N2) extra memory.

  1. Generate all the pairwise sums in O(N2) and store the pair (ai, aj) in a hash table and use the absolute value of their sum as the key of the hash table (ai and aj are two distinct numbers of the input array)

  2. Iterate over the table and find a key which has both negative and positive sum with four distinctive elements and return is as the answer

There is an alternative if you prefer not using hash table. Since your numbers are integers, you can sort the list of all the sum in a linear time of the elements in the sum list using something like a Radix sort (there are O(N2) elements in the sum list).

Tags:

Algorithm

Sum