hardBinary SearchBinary Search

Median of Two Sorted Arrays

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

Recognize the pattern

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

Brute force idea

If you approach Median of Two Sorted Arrays in the most literal way possible, you get this: 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.

Better approach

The deeper shift in Median of Two Sorted Arrays is this: 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.

Key invariant

At the center of Median of Two Sorted Arrays is one steady idea: 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.

Watch out for

A common way to get lost in Median of Two Sorted Arrays is this: 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