Skip to content

visual walkthrough

Median of Two Sorted Arrays

HardBinary Search on PartitionReported at: AmazonAppleMicrosoft+10

The famous O(log(min(m,n))) partition problem.

Solve on LeetCode

The idea

The median splits all the numbers into a smaller half and a bigger half. Choosing how many come from the first array fixes how many come from the second.

Binary search that one number: if the left side has something too big from one array, take fewer from it.

Complexity

approachtimespace
Merge up to the middleO(m + n)O(m + n)
Binary search the cutO(log min(m, n))O(1)

More walkthroughs