hardBinary SearchBinary Search

Median of Two Sorted Arrays

hardTime: O(log(min(m,n)))Space: O(1)

Signals to notice

find median of two sorted arraysO(log(m+n)) requiredbinary search on partition

Brute force first

Merge both arrays and find the middle element. Correct but doesn't meet the requirement. It is a fair place to begin because it matches the surface of the question, yet it does not capture the deeper structure that makes the problem simpler.

The key insight

Binary search on the partition point of the smaller array. Partition both arrays such that left halves contain the smaller half of all elements. The median is at the partition boundary. O(log(min(m,n))). Once you hold onto the right piece of information from moment to moment, the problem feels less like trial and error and more like following a shape that was there all along.

What must stay true

If you partition both arrays such that every element in the left halves ≤ every element in the right halves, and left halves have exactly ⌊(m+n+1)/2⌋ elements total, then the median is at the boundary. When you keep that truth intact, each local choice supports the larger solution instead of fighting it.

Easy way to go wrong

Binary searching both arrays — only search the smaller one. The other array's partition is determined: partitionB = (m+n+1)/2 - partitionA. Most mistakes here are not about syntax; they come from losing track of what your state, pointer, or structure is supposed to mean.

Binary Search Pattern