Median of Two Sorted Arrays
hardLeetCode Top 100binary-searcharrays
Problem
Given two ascending sorted arrays, return the median of their combined ordering in logarithmic time relative to the smaller array.
Examples
Input: a = [1, 3], b = [2]
Output: 2.0
Merged order is [1, 2, 3] with median 2.
Input: a = [1, 2], b = [3, 4]
Output: 2.5
Merged order [1, 2, 3, 4] has median 2.5.
Constraints
- • 0 <= each array length <= 1000
- • Combined length is at least one
- • Both arrays are sorted ascending
Hints(tap to reveal)
- 1. Binary search a partition of the smaller array.
- 2. A valid partition balances counts and orders the boundary values.
Optimal approach(spoiler)
- Binary search the cut position in the smaller array.
- Derive the complementary cut in the larger array so left and right halves balance.
- Check that the largest left elements do not exceed the smallest right elements.
- From a valid partition compute the median from the boundary values.
- O(log(min(m, n))) time, O(1) space.
Ready to solve it?
Write your solution in the editor and get an instant AI grade on correctness, edge cases, and complexity.
Practice in the editor