The Runtime Theory
hardleetcode#binary-search#array

Median of Two Sorted Arrays

Find the median of two sorted arrays in O(log(min(m,n))) by binary searching a partition cut across both arrays.

The Runtime Theory Team1 min read
Solve it

solving happens on the judge — come back and mark it done

Sample cases

in[1,3], [2]

out2.00000

in[1,2], [3,4]

out2.50000

in[], [1]

out1.00000

The machine must find the median of two sorted arrays in O(log(min(m,n))). Merging is O(m+n) — correct but too slow. The insight: the median is a cut. Cut both arrays so the left halves hold exactly the same count of elements and every left element is ≤ every right element; then the median derives from the four elements at the cuts. Binary search the cut position in the smaller array; the other cut is then determined.

python
def find_median_sorted_arrays(a, b):
    if len(a) > len(b):
        a, b = b, a
    m, n = len(a), len(b)
    lo, hi = 0, m
    while lo <= hi:
        i = (lo + hi) // 2
        j = (m + n + 1) // 2 - i
        a_left = a[i - 1] if i > 0 else float("-inf")
        a_right = a[i] if i < m else float("inf")
        b_left = b[j - 1] if j > 0 else float("-inf")
        b_right = b[j] if j < n else float("inf")
        if a_left <= b_right and b_left <= a_right:
            if (m + n) % 2:
                return max(a_left, b_left)
            return (max(a_left, b_left) + min(a_right, b_right)) / 2
        if a_left > b_right:
            hi = i - 1
        else:
            lo = i + 1

Steps: (1) binary search the cut in the smaller array, (2) derive the second cut from the total length, (3) check the cross conditions; when they hold, compute the median from the boundary elements.

Time is O(log(min(m,n))). Space is O(1). The ±inf sentinels handle cuts at the edges.

Trickiest edge case: an empty array — sentinels carry the comparisons, and j must stay in bounds. Even vs odd total length changes which elements combine. Duplicates at the cut boundaries are fine; only the ≤ conditions matter.

More practice in this topic

One dispatch a week

The trace behind each problem, the tradeoff that explains it, and one technical dispatch per week — no noise.

One technical dispatch per week. No noise.