Full answer
Problem
Given sorted lists a (length m) and b (length n), return the median of all m + n values as a float.
Example: a = [1, 3], b = [2] gives 2.0; a = [1, 2], b = [3, 4] gives 2.5.
Constraints: 0 <= m, n <= 1000, m + n >= 1 (both empty raises ValueError), required time O(log(m + n)) or better.
Brute force
Merge (or concatenate and sort) and pick the middle: O(m + n) with a merge, O((m + n) log(m + n)) with sorting. The test uses this as the reference.
Optimal approach
- Make
athe shorter list. Lethalf = (m + n + 1) // 2, the size of the left part. - Binary search
iin[0, m], the count taken froma; thenj = half - ifromb. - Read the edge values, using minus and plus infinity past the ends:
a_left = a[i - 1],a_right = a[i],b_left = b[j - 1],b_right = b[j]. - If
a_left <= b_rightandb_left <= a_right, the cut is correct:- odd total: median is
max(a_left, b_left); - even total:
(max(a_left, b_left) + min(a_right, b_right)) / 2.
- odd total: median is
- If
a_left > b_right, too many were taken froma:hi = i - 1. Otherwiselo = i + 1.
Why it works
The median splits the combined values into a left part of size half and a right part, with every left value at most every right value. Each list is already sorted, so only the cross pairs (a_left with b_right, b_left with a_right) can violate that. As i grows, a_left grows and b_right shrinks, so the violations are monotonic in i, which makes binary search valid. Searching the shorter list keeps j in [0, n].
Complexity
O(log(min(m, n))) time, O(1) space.
Code
def find_median_sorted_arrays(a, b):
"""Median of two sorted lists in O(log(min(m, n))) by binary searching a partition."""
if len(a) > len(b):
a, b = b, a # binary search the shorter list
m, n = len(a), len(b)
if m + n == 0:
raise ValueError("both lists are empty")
half = (m + n + 1) // 2 # size of the left part
lo, hi = 0, m
while lo <= hi:
i = (lo + hi) // 2 # take i items from a ...
j = half - i # ... and j items from b
a_left = a[i - 1] if i > 0 else float("-inf")
a_right = a[i] if i < m else float("inf")
b_left = b[j - 1] if j > 0 else float("-inf")
b_right = b[j] if j < n else float("inf")
if a_left <= b_right and b_left <= a_right:
if (m + n) % 2:
return float(max(a_left, b_left))
return (max(a_left, b_left) + min(a_right, b_right)) / 2
if a_left > b_right:
hi = i - 1 # took too many from a
else:
lo = i + 1 # took too few from a
raise AssertionError("inputs must be sorted")
def brute(a, b):
c = sorted(a + b)
mid = len(c) // 2
return float(c[mid]) if len(c) % 2 else (c[mid - 1] + c[mid]) / 2
if __name__ == "__main__":
for f in (find_median_sorted_arrays, brute):
assert f([1, 3], [2]) == 2.0
assert f([1, 2], [3, 4]) == 2.5
assert f([], [1]) == 1.0
assert f([0, 0], [0, 0]) == 0.0
assert f([2], []) == 2.0
assert f([1, 2, 3, 4, 5], [6, 7, 8, 9, 10, 11]) == 6.0
try:
find_median_sorted_arrays([], [])
raise AssertionError("expected ValueError")
except ValueError:
pass
print("all tests passed")Save as a32_median_two_arrays.py and run python3 a32_median_two_arrays.py. It prints all tests passed (Python 3.13.5).
Edge cases
One list empty. All values equal. All of a smaller than all of b (cut at an end, handled by the infinities). Odd and even totals. Both empty is rejected. Unsorted input breaks the precondition; the code raises AssertionError if no valid cut is found.
Pattern
Binary search on a partition position. The generalisation is "k-th smallest of two sorted arrays", solved by discarding about k / 2 elements per step.
def find_median_sorted_arrays(a, b):
"""Median of two sorted lists in O(log(min(m, n))) by binary searching a partition."""
if len(a) > len(b):
a, b = b, a # binary search the shorter list
m, n = len(a), len(b)
if m + n == 0:
raise ValueError("both lists are empty")
half = (m + n + 1) // 2 # size of the left part
lo, hi = 0, m
while lo <= hi:
i = (lo + hi) // 2 # take i items from a ...
j = half - i # ... and j items from b
a_left = a[i - 1] if i > 0 else float("-inf")
a_right = a[i] if i < m else float("inf")
b_left = b[j - 1] if j > 0 else float("-inf")
b_right = b[j] if j < n else float("inf")
if a_left <= b_right and b_left <= a_right:
if (m + n) % 2:
return float(max(a_left, b_left))
return (max(a_left, b_left) + min(a_right, b_right)) / 2
if a_left > b_right:
hi = i - 1 # took too many from a
else:
lo = i + 1 # took too few from a
raise AssertionError("inputs must be sorted")
def brute(a, b):
c = sorted(a + b)
mid = len(c) // 2
return float(c[mid]) if len(c) % 2 else (c[mid - 1] + c[mid]) / 2
if __name__ == "__main__":
for f in (find_median_sorted_arrays, brute):
assert f([1, 3], [2]) == 2.0
assert f([1, 2], [3, 4]) == 2.5
assert f([], [1]) == 1.0
assert f([0, 0], [0, 0]) == 0.0
assert f([2], []) == 2.0
assert f([1, 2, 3, 4, 5], [6, 7, 8, 9, 10, 11]) == 6.0
try:
find_median_sorted_arrays([], [])
raise AssertionError("expected ValueError")
except ValueError:
pass
print("all tests passed")Partition binary search on the shorter list with infinity sentinels; a sort-based reference is tested on the same inputs.
Complexity
Time: O(log(min(m, n))). Space: O(1). Merging would be O(m + n); the partition search avoids reading most elements.
By level
Fresher: Gives the merge solution, then explains the idea of cutting both lists so the left halves have the right size. Should state the cost of the merge approach.
Mid: Implements the partition search with sentinels and explains why the conditions are monotonic. Explains the role of the infinity sentinels.
Senior: Generalises to k-th smallest, compares with streaming median using two heaps, and proves the bound on iterations. Can explain why the shorter list must be the one searched.
Key points
- Binary search the number taken from the shorter list
- j = half - i fills the left part
- Valid cut: a_left <= b_right and b_left <= a_right
- Use infinities past the ends
- O(log(min(m, n)))
Common mistakes
- Searching the longer list so j goes negative
- Forgetting the empty-side cases
- Wrong median formula for odd totals
- Integer division where a float median is expected
Follow-ups
- How would you find the k-th smallest of two sorted arrays?
- What about the median of k sorted arrays?
- How would you maintain a running median of a stream?
Tips
- Start from the merge solution and its cost
- Draw the cut on both lists
- State the two cross conditions clearly
Evaluation rubric
- Correct partition logic
- Handles empty and boundary cuts
- Correct odd and even formulas
- Correct complexity