tags:

views:

159

answers:

3

Given an array A of integers, find any 3 of them that sum to any given T.

I saw this on some online post, which claims it has a O(NlogN) solution.

For 2 numbers, I know hashtable could help for O(N), but for 3 numbers, I cannot find one.

I also feel this problem sounds familar to some hard problems, but cannot recall the name and therefore cannot google for it. (While the worst is obviously O(N^3), and with the solution to 2 numbers it is really O(N^2) )

It does not really solve anything in the real world, just bugs me..

Any idea?

+1  A: 

Sounds like a homework question...

If you can find two values that sum to N but you want to extend the search to three values, couldn't you, for each value M in the set, look for two values that sum to (N - M)? If you can find two values that sum to a specific value in O(log N) time, then that will be O(N log N).

Tim Sylvester
How are you going to find two numbers that sum to a specific value in log(N) time?
Peter Recore
Good question, I don't know. I didn't say it was possible, only that you would need to be able to do it in order solve the problem in the particular way that I described.
Tim Sylvester
+4  A: 

I think your problem is equivalent to the 3SUM problem.

Nick D
Thanks Nick, and guys for the answers. I am constantly bugged by this kind of questions, where a logic sounds familar but there is no answer by string matching based searches. Would open another thread on it.
Dr. Xray
A: 

I think this is just the subset sum problem

If so, it is NP-Complete.

EDIT: Never mind, it is 3sum, as stated in another answer.

Peter Recore
There are less than n^3 ways to pick 3 numbers among n, so it can hardly be NP-complete. The trivial brute-force algorithm is O(n^3).
Pascal Cuoq
yup. the subset problem is NP, but this is not the subset problem. the subset problem doesn't specify how many numbers will be added together, while this problem restricts it to exactly 3.
Peter Recore