Median of Two Sorted Arrays
Problem
You are given two sorted arrays of integers, possibly of different lengths. Return the median of the combined set of all their values, as if the two arrays had been merged into one sorted array.
Example. For [1, 2] and [3, 4], the merged order is [1, 2, 3, 4], so the median is the average of the two middle values, 2 and 3, which is 2.5.
Key idea
Merging the two arrays and reading off the middle works, but costs time proportional to their combined length: more than is needed, since a median only requires knowing what lies on either side of one dividing point. The insight is to binary search directly for that dividing point, called a partition, without ever materializing the merge.
Pick a partition index in the shorter array, which fixes a matching partition in the longer array so the two together hold exactly half the elements on the left. A partition is correct when every element just left of the cut is no greater than every element just right of it, in both arrays. If the shorter array's left side is too large, move the partition left; otherwise move it right. Because shifting it changes those comparisons monotonically, the search converges quickly, and the median then comes directly from the boundary values.
Solution
Complexity
- Time: O(log(min(n, m))). Binary search runs over the shorter array's index range.
- Space: O(1). Only a handful of boundary values and indices are kept.
Watch out for
- Binary search over the shorter array, not the longer one, or the partition math and edge-index bounds can go out of range.
- Partitions at the very start or end of an array leave one side empty; treat that missing boundary as negative or positive infinity rather than a real value.
Pattern
This is binary search over a partition rather than a single value: the search narrows in on a split point defined by a cross-array balance condition, not a comparison to a fixed target. It is the sharpest example of turning a merge-like problem into a logarithmic search over the answer's structure.