I've been stuck on this question for a very long time. Let X, Y, and Z be sets of n integers. Let k be any integer. The question "Can you find an x in X, y in Y and z in Z such that x + y + z = k" can be obviously solved in O(n^3) time by trying all the combinations. Give an algorithm that runs in O(n^2). You may assume that sort is a built-in method that runs in O(n*log n) time. This was a question from an old test. Any help will be appreciated. Thanks.
2 Answers
Any help will be appreciated.
My help is in the form of hints.
Hints:
1 - If x + y + z == k, then z = k - x - y ...
2 - How can you test for set membership in O(1)? (Which ignores the hint in the question ...)
OR
2a - What is O(N log N) when N is M * M ? (And why did I pick O(N log N) ??)
3 Comments
paxdiablo
That's a very vague hint, you still have to cycle through three arrays which makes it still O(n^3). Perhaps, in the interests of providing useful answers, you could clarify a bit :-)
Stephen C
No ... you don't. The question contains another fact. My answer is stated in the form it is in the interest of getting the OP to think about it, which is probably more in his interests than providing a potted answer.
paxdiablo
I'm not going to vote you down, S, since I got it. But I have rather a lot of years under my belt :-) OP may not have that advantage. Even if you pointed to that extra fact, it may go some way towards answering at OPs level while still requiring some thought. ... Never mind, you added it during my comment.
Sort the array.
For each z in the array, check if k-z is the sum of two elements, in O(n) time (classic interview question and solution, you will find a lot of pages containing that).
1 Comment
ad56
So I sort all the arrays, and then for each z in Z, I check if k-z is the sum of an x in X and a y in Y. This can be easily achieved in O(n) time if X and Y are sorted, and hence overall time O(n^2) because you have to do this for all n elements in Z. Correct?