Forward Deployed EngineeringCoding and AlgorithmsBinary Search

Find the median of two sorted arrays in logarithmic time

Question 8 of 9 · Updated

On this page

Interview-ready answer#

I would exploit the fact that both arrays are sorted. Merging them takes linear time, so instead I binary-search a partition in the shorter array. The complementary partition in the other array is determined by the number of elements that must lie on the left: (m + n + 1) // 2.

A partition is valid when the largest element on either left side is no greater than the smallest element on the opposite right side. For an odd total length, the median is the maximum of the two left boundary elements. For an even total length, it is the average of the largest left element and smallest right element. Searching only the shorter array gives O(log(min(m,n) + 1)) iterations and O(1) auxiliary space.

How the binary partition works#

Let a and b be sorted arrays of lengths m and n, with m <= n. Assume random access, finite integer elements, and at least one nonempty array.

Choose i elements from a for the left partition. The number taken from b must be j = (m + n + 1) // 2 - i. Since we search 0 <= i <= m and m <= n, j remains between zero and n.

a: [ ... a_left | a_right ... ]
b: [ ... b_left | b_right ... ]
             left | right

Valid if a_left <= b_right and b_left <= a_right

Use negative infinity for a missing left boundary and positive infinity for a missing right boundary. Sortedness already guarantees the order within each array; the cross-boundary comparisons ensure that every element in the combined left partition is no greater than every element in the right partition.

  • If a_left > b_right, too many elements were taken from a; move the binary search left.
  • If b_left > a_right, too few elements were taken from a; move right.
  • Otherwise, the partition is valid and the median follows directly.

These corrections are monotonic: moving the cut to the right increases (or preserves) the boundaries in a while moving the complementary cut to the left decreases (or preserves) those in b. Thus each failed check eliminates a half of the remaining search space. A valid partition exists because the smallest half of the combined sorted order can be represented by prefixes of the two inputs.

Worked example#

For a = [1, 3, 8] and b = [7, 9, 10, 11], the total length is 7, so the left partition needs 4 elements.

ija_lefta_rightb_leftb_rightDecision
13131011Move right: 10 > 3
2238910Move right: 9 > 8
318+∞79Valid partition

The left elements are [1, 3, 8, 7]; the right elements are [9, 10, 11]. The total is odd, so the median is max(8, 7) = 8. No merged array is required.

Python implementation#

PYTHON
from math import inf def median_sorted(a: list[int], b: list[int]) -> float: if len(a) > len(b): a, b = b, a m, n = len(a), len(b) if m + n == 0: raise ValueError('Both arrays are empty') half = (m + n + 1) // 2 lo, hi = 0, m while lo <= hi: i = (lo + hi) // 2 j = half - i al = a[i-1] if i else -inf ar = a[i] if i < m else inf bl = b[j-1] if j else -inf br = b[j] if j < n else inf if al > br: hi = i - 1 elif bl > ar: lo = i + 1 else: left = max(al, bl) if (m + n) % 2: return left return (left + min(ar, br)) / 2 raise ValueError('No valid partition found') print(median_sorted([1, 3], [2])) # 2 print(median_sorted([1, 2], [3, 4])) # 2.5 print(median_sorted([], [7])) # 7

The function assumes sorted inputs; the fallback exception is not a comprehensive sortedness validator. Checking every element for sortedness would require linear time. Python integers avoid fixed-width addition overflow, but floating-point division can lose precision for very large integers; use exact rational arithmetic if the application requires it.

Complexity and alternatives#

ApproachTimeAuxiliary space
Merge both arraysO(m+n)O(m+n)
Two pointers, stopping at medianO(m+n)O(1)
Binary partitionO(1 + log(min(m,n)+1))O(1)

The binary-partition bound is commonly written O(log(min(m,n))) for nontrivial input sizes, and also satisfies the requested O(log(m+n)) bound. An empty shorter array requires only one partition check. Unlike merging, binary partition requires efficient random access to both sorted sequences.

Local verification: 15,882 checks passed. All 15,875 ordered nonempty-total pairs drawn from 126 sorted sequences of lengths 0–4 over values -2 through 2 were compared with Python's statistics.median on the combined elements. Six additional explicit cases, including a strongly unbalanced input, and the both-empty exception were also checked.

FDE production perspective#

Imagine two customer systems exporting already-sorted transaction amounts, and a dashboard requiring the exact combined median. If both snapshots are consistent, disjoint by design (or duplicates intentionally count), and support efficient indexed access, the algorithm can compute the median without materializing a merged dataset. It does not work by averaging the two individual medians; the relative ordering and sample sizes matter.

For distributed or streaming systems, each random probe might trigger a network request, and sorted snapshots may not exist. I would first validate consistency, deduplication rules, units, and latency requirements. For repeated or approximate percentile queries at scale, evaluate server-side rank selection or mergeable quantile sketches rather than assuming this in-memory algorithm is the right production architecture. Approximate quantiles must have documented error bounds and be acceptable to the customer.

Likely interviewer follow-ups#

  • Why binary-search the smaller array? It minimizes the search space and keeps the complementary partition index within the longer array's bounds.
  • What about duplicate elements? Non-strict boundary comparisons (<=) allow ties correctly.
  • How do you find the kth smallest element instead? Set the left partition size to k, constrain i to [max(0, k-n), min(k, m)], and return the maximum left boundary.
  • What if the arrays are unsorted? This algorithm no longer applies. Consider selection algorithms or sorting, depending on the input and whether mutation is allowed.

Related questions

Explore other topics:AI AgentsAI System DesignLarge Language Models