0

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.

1
  • You can also think of it this way: if x, y, and k are known, is there a way to check if z is an element of Z efficiently? Commented Sep 26, 2014 at 9:09

2 Answers 2

1

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) ??)

Sign up to request clarification or add additional context in comments.

3 Comments

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 :-)
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.
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.
0

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

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?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.