2

Given 3 sorted array. Find 3 elements, one from each array such that a+b=c. Can it be done less than O(n^3) time complexity? Please help me.

2 Answers 2

4

Call the three arrays A, B and C, and the elements a, b and c.

While looping through the first two arrays, since if a is fixed, b can only increase, c also can only increase.

So you don't have to loop through C every time you have a pair of a and b; just loop through C while looping though B will do.

Now Suppose all three arrays have length O(N), the time complexity is O(N^2), since for each value in A, you need to go through all of B and all of C, the number which is O(N).

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

Comments

2

It can be done in O(N^2 * logN) complexity by iterating through 2 of the arrays for a and b and binary searching for c in the third array.

Another method would be O(N^2) by inserting the elements of one of the arrays into a hash, iterate for a and b in the other two arrays and looking if c = (a + b) exists in the hash.

2 Comments

For method 2, is there any efficient way to solve it since it is given that all 3 arrays are already sorted?
You can't generate the (a,b) pairs better than O(N^2) ... The searching in the hash is O(1)

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.