Finding median of union of two sorted (ordered) lists

795 Views Asked by At

We are given two sorted list of numbers $a_1, a_2, \ldots, a_n$ and $b_1, b_2, \ldots, b_n$. Question is, how to find a median for list $a_1, a_2, \ldots, a_n, b_1, b_2, \ldots, b_n$. Algorithm should be able to find median in $\mathcal{O}(\log n)$.

I can't find better way but $\mathcal{O}(n \log n)$.

Also, I'm familiar with algorithm that finds median in $\mathcal{O}(\log k)$ for sorted list $c_1, c_2, \ldots, c_k$, I just can't find a way to use that.

EDIT: That last comment was indeed incorrect. For unsorted list, we can find median in $\mathcal{O}(n)$ expected time. In theory, it is still $\mathcal{O}(n^2)$.

2

There are 2 best solutions below

1
On BEST ANSWER

Assume without loss of generality that the median is among the $a_i$'s. (Why can we assume this?) Suppose that it is actually $a_k$. We will use binary search to find $k$.

For any current guess $k'$, if $a_{k'}>b_{n-k'}$ and $a_{k'}<b_{n-k'+1}$, then $a_{k'}$ is the median. (Why?) Otherwise, $k'$ is either too low or too high, and we perform binary search accordingly. Since we only perform binary search on one list of length $n$, the algorithm runs in $O(\log n)$.

1
On

Hint. If $a_{\left[\frac n2\right]} > b_{\left[\frac n2\right]}$ then what can you say about median?