O(n^2 * logn) can be achieved by:
- Array Sort - O (nlogn)
- repeat all pairs (O (n ^ 2) of them) - and for each pair (x, y) perform a binary search to see if you have:
max{x,y} + abs(xy) or min{x,y} - abs(xy) as an element.
Particular attention should be paid to pairs where x==y - but it can be easily solved with the same complexity in time.
Please note that this solution will give you 1 view of each triplet (no duplicates).
( EDIT: using a hash table ( histogram if you care about the number of triplets) and look in it instead of sorting the array and using binary search - you can reduce the time to O(n^2) on average, at a cost of O(n) extra space).
Without 1 minus failures - this cannot be done better than O(n^3) , because there can be O(n^3) such triplets, for example, in an array [1,1,1,...,1] - you have chose(3,n) such triplets.
source share