Problem
Given two sorted arrays of sizes m and n, return the median of the two arrays combined. The required run time is O(log(m + n)).
Approach
Merging the arrays would take linear time, so instead binary search for a partition. Split both arrays so that the left halves together hold half of all the elements.
Binary search over the cut position in the shorter array; the cut in the longer array follows from it. A partition is correct when the largest value on the left side of each array is no bigger than the smallest value on the right side of the other array.
Once the partition is correct, the median is the largest left value for an odd total, or the average of the largest left value and the smallest right value for an even total. Treat a cut at either end of an array as negative or positive infinity.
The solution files below implement this approach.
Complexity
- Time: O(log(min(m, n))): the binary search runs over the shorter array.
- Space: O(1).
Edge cases
- One array can be empty; the median then comes from the other array alone.
- Arrays of very different lengths are why the search runs over the shorter one.
- Even and odd combined lengths need different final steps.