codejump
HardPro challengePythonJavaScriptTypeScript

Binary Search — Median of Two Sorted Arrays

AlgorithmsBinary SearchDivide and ConquerArrays

solve(a, b) — a and b are sorted ascending and not both empty. Return the
median of the combined values: the middle one when the total count is odd, the
average of the two middle ones when it is even. Run in O(log(min(m, n))).

Merging is O(m + n). The trick is to binary search a partition of the shorter array:
cut a after i elements and b after j = half - i elements, so the left side holds
the lowest half of all values. The cut is right when a[i-1] <= b[j] and
b[j-1] <= a[i]; use -Infinity / Infinity for a missing neighbour.

Examples

solve([1,3], [2])        → 2
solve([1,2], [3,4])      → 2.5
solve([], [1])           → 1

Sample tests

Test #1Odd total
Input: [[1,3],[2]]
Output: 2
Test #2Even total
Input: [[1,2],[3,4]]
Output: 2.5
Test #3One array empty
Input: [[],[1]]
Output: 1