Given a list [a_1 a_2 ... a_n] of (not necessarily distinct) integers, determine whether there exist pairwise distinct indices w,x,y,z such that a_w + a_x = a_y + a_z.
I know that one way is to use 4 levels of for loops, each one iterating over one of the indices. When we get equal sums, check whether all the indices are pairwise distinct. If they are, return true. If we’ve exhausted all the possibilities, return false. This has running time O(n^4).
Can we do better?
Compute all possible values for
a_w + a_x, insert them to hash table. Insert (a_w + a_x, w) and (a_w + a_x, x) to second hash table.Prior to inserting a value to first hash table, check if it is already in the table. If so, check second table. If either of (a_w + a_x, w) or (a_w + a_x, x) is there, don’t insert anything (we’ve got a duplicate element). If neither of these pairs is in the second table, we’ve got positive answer.
If, after processing all (w, x) pairs, we’ve got no positive answer, this means there is no such pairwise distinct indices.
Time complexity is O(n2). Space requirements are also O(n2).
It is possible to do the same in O(n) space but O(n2 * log(n)) time with slightly modified algorithm from this answer: Sum-subset with a fixed subset size:
a_w + a_xas a key andw, xas values. Pre-fill this queue withn-1elements, where x = 0 and w = 1 .. n-1.(sum, w, x)from this queue and put element(a_w + a_x_plus_1, w, x+1)to the queue (but don’t put elements when x >= w). Stop when two consecutive elements, removed from queue, have the same sum.