two sorted array A, B
with length n,m
(n <= m)
, and k
which (k >= log n)
is given.
with log (nm)
we can find k-th
smallest number in union of these two array.
I have a solution In problem 2 here, but my challenge is why two given condition "(n <= m)" and "k >= log n" does not affect this algorithm?
CodePudding user response:
First assumption:
n <= m
is an assumption "without loss of generality". If n >= m, then just swap A and B in your head. They included this assumption even though it was not needed, because they felt it was "free" to make this assumption.Second assumption: A trivial algorithm to find the
k
th smallest element is to iterate over A and B simultaneously, advancing in the array that has the smaller element of the two. This would be exactly like running the "Merge" function from mergesort, but stopping once you've merged the first k elements. The complexity would be O(k). They wanted you to find a more complex algorithm, so they "ruled out" this algorithm by stating that k >= log(n), which implies that complexity O(k) is never better than O(log(n)). Technically, if they wanted to thoroughly rule this algorithm out, they should also have stated thatk <= n m - log(n)
, otherwise you could run the "merge" function from the end: merge the n m-k largest elements, then return then m-k
th largest element, which is the same as the kth smallest element.