Given an array of integers [a1 a2 ... an], not necessarily distinct, give an algorithm that returns “yes” if there are distinct indices i,j,k such that ai + aj = ak, and “no” otherwise.
Is there a way to do this faster than brute force, which takes O(n^3)?
build a list of all possible sums ai + aj: O(n^2).
The list wil have size=n^2
then compare that list with the array, to see whether there are any similarities:
total: O((n^2)log(n^2)) ( = O((n^2)log(n)) per comment from alestanis)
edit: i forgot about the distinct requirement, but that should not change the result.
first, to assure i!=j, just exclude i==j when building the list of all sums in step 1.
second, to assure i!=k and j!=k, tag each sum with its indices i,j, and tag each original value with its index k before sorting.
then in the last step when you find any match, check whether the tagged indices are distinct.