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:
- Sort the list.
- Use a priority queue for elements, containing
a_w + a_x
as a key and w, x
as values. Pre-fill this queue with n-1
elements, where x = 0 and w = 1 .. n-1.
- Repeatedly pop minimal element
(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.
- To handle duplicates, it is possible to compare w, x of two consecutive elements, having equal sum. But it's easier to use krjampani's idea of pre-processing. If sorted list contains two pairs of duplicates or a single element is duplicated 4 times, success. Otherwise no more than a single value is duplicated; leave only single instance of it in the list and add its doubled value into priority queue along with a "special" pair of indexes: (2a, -1, -1).