Divide & conquerAnimated
Median of Two Sorted Arrays
Binary search the partition between the arrays.
Time
O(log(min(n, m)))
Extra space
O(1)
Use it for
Combining sorted sources.
How it works
- The median splits all the numbers into a left half and a right half of (almost) equal size, where everything on the left is ≤ everything on the right.
- Instead of merging, binary search how many items i to take from the shorter array for the left half. The longer array supplies the rest, j = half − i.
- The split is correct when the last left item of each array is ≤ the first right item of the other array.
- If not, move the cut left or right. O(log min(m, n)).
Watch it run
Loading animation…