patternMinor
Hint on median of two sorted lists, logarithmic time
Viewed 0 times
hintlogarithmictimetwolistssortedmedian
Problem
I'm looking for a hint to help me think through/solve the problem of finding the median of two sorted lists/arrays in O(log(m+n)) time, where m,n are the sizes/lengths of each list, respectively.
I can immediately think of an obvious O(m+n) time algorithm using big-theta of m+n space, as follows: Merge the two lists into a new list in O(m+n) time. Find the middle element of that list in O(1) time (more particularly, if the merged list is even in length, take the mean of the floor of the element at index (m+n)/2, and the ceiling of the element at index (m+n)/2, otherwise the merged list length is odd and just use the element at (m+n)/2... potentially update logic for off-by-one depending on zero- or one-indexing).
But I don't immediately see how the median could be found in logarithmic time. Any hints would be appreciated!
I can immediately think of an obvious O(m+n) time algorithm using big-theta of m+n space, as follows: Merge the two lists into a new list in O(m+n) time. Find the middle element of that list in O(1) time (more particularly, if the merged list is even in length, take the mean of the floor of the element at index (m+n)/2, and the ceiling of the element at index (m+n)/2, otherwise the merged list length is odd and just use the element at (m+n)/2... potentially update logic for off-by-one depending on zero- or one-indexing).
But I don't immediately see how the median could be found in logarithmic time. Any hints would be appreciated!
Solution
Let say you have the two sorted array arrange as follow, using uppercase letter to represent a sequence of numbers and a lowercase letter to represent a single number:
[A,p,B] and [C,q,D]
Now suppose p > q, you know [A, p] and [C] > [q, D], then what can you do with this fact?
[A,p,B] and [C,q,D]
Now suppose p > q, you know [A, p] and [C] > [q, D], then what can you do with this fact?
Context
StackExchange Computer Science Q#85410, answer score: 3
Revisions (0)
No revisions yet.