Calculate all possible values ββfor a_w + a_x , insert them into the hash table. Insert (a_w + a_x, w) and (a_w + a_x, x) into the second hash table.
Before inserting a value into the first hash table, check if it is already in the table. If yes, check the second table. If there is one of (a_w + a_x, w) or (a_w + a_x, x), do not insert anything (we have a duplicate element). If none of these pairs is in the second table, we have a positive answer.
If, after processing all (w, x) pairs, we do not have a positive answer, this means that there are no such pairwise different indices.
The complexity of time is O (n 2 ). Space requirements are also O (n 2 ).
You can do the same in O (n) space, but O (n 2 * log (n)) time with a slightly modified algorithm from this answer: Sum-subset with a fixed size of the subset :
- Sort list.
- Use a priority queue for items containing
a_w + a_x as a key and w, x as values. Pre-fill this queue with elements n-1 , where x = 0 and w = 1 .. n-1. - Re-enter the minimum element
(sum, w, x) from this queue and put the element (a_w + a_x_plus_1, w, x+1) in the queue (but do not put the elements when x> = w). Stop if two consecutive items removed from the queue have the same sum. - To handle duplicates, you can compare w, x of two consecutive elements that have an equal sum. But itβs easier to use krijampani for pre-processing. If the sorted list contains two pairs of duplicates or one element is duplicated 4 times, success. Otherwise, no more than one value is duplicated; leave only one copy of this list in the list and add its doubled value to the priority queue together with the βspecialβ pair of indices: (2a, -1, -1).
Evgeny Kluev
source share