I have this question:
Given two sorted lists (stored in arrays) of size n, find an O(log n)
algorithm that computes the nth largest element in the union of the
two lists.
I can see there is probably a trick here as it requires the nth largest element and the arrays are also of size n, but I can’t figure out what it is. I was thinking that I could adapt counting sort, would that work?
Compare A[n/2] and B[n/2]. If equal, any of them is our result. Other stopping condition for this algorithm is when both arrays are of size 1 (either initially or after several recursion steps). In this case we just choose the largest of A[n/2] and B[n/2].
If A[n/2] < B[n/2], repeat this procedure recursively for second half of A[] and first half of B[].
If A[n/2] > B[n/2], repeat this procedure recursively for second half of B[] and first half of A[].
Since on each step the problem size is (in worst case) halved, we’ll get O(log n) algorithm.
Always dividing array size by two to get the index works properly only if
nis a power of two. More correct way of choosing indexes (for arbitraryn) would be using the same strategy for one array but choosing complementing index:j=n-ifor other one.