I have two arrays. Array A contains n elements, array B contains m elements, and m < n. They are sorted in ascending order. I want to find all the matches between the two arrays. Two adjacent elements in array A may correspond to the same element of array B.
There are two constraints:
The algorithm should have a time complexity of O(n)
I can only compare each element in A a limited number of times with values in B: at most ceil(log(n)) times. This means at most one binary search can be performed per value in A.
To compare the elements, I need to use a compare function that runs in O(1). This function can have three different return values:
- if the two given values match, or
- the first is less than the second, or
- the first is greater than the second.
So we cannot simply merge the two arrays.
How can I finish this in O(n) time?
I have tried the following ways:
Compare each element of these two arrays from beginning to the end. However, if all of A's elements match B's last element we will exceed the compare time limitation of ceil(log(n)).
Pick the middle element of A, binary search it in B, and then split the B array into 2 partitions. If we do not consider the worst situation, the overall time complexity is determined by
T(n) = 2T(n/2) + logm,...which is OK. However, in the worst case, all of A's elements correspond to the minimum or maximum element in B, and then the time complexity is determined by
T(n) = 2T(n/2) + logm,...which is not O(n).
I am out of other ideas. How can I design this algorithm with the given constraints? Or maybe I have a mistake in how I calculated the time complexity?