AAI Agentic Handbook
Problem 18 · Binary Search

Median of Two Sorted Arrays

HardClassic DSA & systems
01Problem

Given two sorted arrays, return the median of their combined elements in O(log(min(m, n))).

02Key insight

Binary search a partition of the shorter array so the left halves of both together hold half the elements and every left element <= every right element; the median comes from the boundary values.

03Solution

Try it first.

TimeO(log min(m, n))
SpaceO(1)
tests.py · 4 passing
tests.pypython4 lines
assert find_median_sorted_arrays([1,3], [2]) == 2.0
assert find_median_sorted_arrays([1,2], [3,4]) == 2.5
assert find_median_sorted_arrays([], [1]) == 1.0
assert find_median_sorted_arrays([1,2,3,4,5], [6]) == 3.5
04Staff-level follow-up

Median across K sorted shards on different machines? Binary search on the value domain, asking each shard for count(<= x) in O(log n), so only counts cross the network; approximate alternative: t-digest/KLL sketches.