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
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).
Comments
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.