Skip to content
StackDecode
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

  1. 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.
  2. 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.
  3. The split is correct when the last left item of each array is ≤ the first right item of the other array.
  4. If not, move the cut left or right. O(log min(m, n)).

Watch it run

Loading animation…