Learn / Binary search

Median of two sorted arrays

To find the k-th smallest of two sorted arrays without merging them, choose how many of the k come from the first array. That choice is right exactly when the last values taken from each side are no bigger than the first values left on the other side, and binary search finds it in O(log(min(m, n))).

How to recognise it

  • Two sorted arrays and a question about the merged order (median, k-th smallest) without merging.
  • The question asks for O(log(m + n)) or better.
  • Splitting one array at some point fixes where the other must be split.

The idea in one picture

Line both arrays up and draw one cut through each. Everything left of the two cuts together should be the k smallest values. The cuts are linked: if the first array gives i values, the second must give k - i. So the only question is where the first cut goes, and that is one binary search.

When is a cut right?

CheckMeaning
a[i - 1] ≤ b[j]the last value taken from a is not too big
b[j - 1] ≤ a[i]the last value taken from b is not too big

If the first check fails, a gave too many: move the cut left. If the second fails, a gave too few: move it right. Missing values off either end count as minus or plus infinity.

Template

make a the shorter array
lo = max(0, k - n), hi = min(k, m)
while lo <= hi:
    i = (lo + hi) / 2, j = k - i
    aLeft = a[i - 1] or -inf, aRight = a[i] or +inf
    bLeft = b[j - 1] or -inf, bRight = b[j] or +inf
    if aLeft <= bRight and bLeft <= aRight: return max(aLeft, bLeft)
    if aLeft > bRight: hi = i - 1
    else: lo = i + 1

For the median, use k = (m + n + 1) / 2. With an odd total, the median is max(aLeft, bLeft). With an even total it is the average of that and min(aRight, bRight).

Common mistakes

  • Merging the arrays, which is O(m + n) and misses the point.
  • Letting i run from 0 to m even when k - i would be negative or bigger than n.
  • Forgetting the infinity values for cuts at the very ends.
  • Averaging two ints in integer arithmetic, which drops the .5.

Problems

0 of 2 solved

Check yourself

You take i values from a and j = k - i from b as the k smallest. When is that split correct?

The split has a[i - 1] > b[j]. What should change?

Why binary search over the shorter array?

For the median of m + n values, how many values should the left part hold?