Median of Two Sorted Arrays
Median of Two Sorted Arrays is LeetCode 4 (Hard). Given two sorted arrays nums1 (length m) and nums2 (length n), return the median of all m + n values taken together.
- The median is the middle value of the combined sorted list, or the average of the two middle values when
m + nis even. - One of the arrays may be empty, but not both.
- The required running time is O(log(m + n)), so merging the two arrays, which is O(m + n), is not the intended answer.
- nums1.length == m
- nums2.length == n
- 0 <= m <= 1000
- 0 <= n <= 1000
- 1 <= m + n <= 2000
- -10⁶ <= nums1[i], nums2[i] <= 10⁶
Intuition
The median splits all the values into a left half and a right half of the same size. You never need to build that combined list. You only need to know how many values each array gives to the left half.
If nums1 gives its first i values, nums2 must give its first j = half - i. Both arrays are sorted, so the split is correct exactly when two border checks pass: the last left value of nums1 is at most the first right value of nums2, and the last left value of nums2 is at most the first right value of nums1. A failed check also tells you which way to move i, so i can be found by binary search.
Two sorted arrays and an order statistic (median, k-th smallest) with a logarithmic time limit means you binary search a split point, not a value. The sorted order is what lets one comparison discard half of the remaining splits.
Approach
Before reading on, take [1, 3, 8, 9, 15] and [7, 11, 18, 19, 21, 25]. The left half must hold 6 values. If the first array gives 2 of them, which values sit on each side of the two cuts, and is that split valid? Aim for O(log min(m, n)).
Two ways to solve it
Binary search how many values the shorter array gives to the left half.
- Meets the limit: logarithmic, as the problem asks.
- Watch out: infinite borders and the swap.
The expected interview answer.
Walk both arrays like the merge step of merge sort and stop at the middle.
- Simple: no border cases to reason about.
- Too slow on paper: linear, not logarithmic.
A good first answer before the follow-up.
With at most 2,000 values both pass, but only the binary search meets the stated O(log(m + n)) limit. The steps, code and live demo follow the binary search; the merge code comes after the demo.
Search the shorter array
Swap the inputs if needed so that nums1 is the shorter one. Then j = half - i stays between 0 and n for every cut i from 0 to m, and the search takes O(log min(m, n)) steps.
Fix the size of the left half
Set half = (m + n + 1) // 2. The + 1 gives the left half the extra value when the total is odd, so the median is then simply the largest value on the left.
Try a cut and read its four border values
With lo = 0 and hi = m, pick i = (lo + hi) // 2 and j = half - i. Read left1 = nums1[i - 1], right1 = nums1[i], left2 = nums2[j - 1] and right2 = nums2[j]. A side with no value gets −∞ (on the left) or +∞ (on the right), so it can never fail a check.
Move the cut toward the valid split
If left1 > right2, nums1 gave too many values, so set hi = i - 1. If left2 > right1, it gave too few, so set lo = i + 1. If neither, every left value is at most every right value and the split is correct.
Read the median from the borders
For an odd total, the median is max(left1, left2), the largest value on the left. For an even total, it is the average of max(left1, left2) and min(right1, right2), the two values that meet in the middle.
Why the search always lands on a valid cut
As i grows, left1 can only grow and right2 can only shrink, so the check left1 > right2 switches from false to true at most once. Likewise left2 > right1 can only switch from true to false. The cut taken from the real merged order passes both, and every failed check points toward it.
Code in Python, C++ and Java
Merge up to the middle
Take the smaller front value of the two arrays, one at a time, exactly as merge sort would, but stop once the middle is reached. Only the last two values taken are kept: the last one is the median for an odd total, and the last two are averaged for an even total.
Common pitfalls
Binary searching the longer array
m, n = len(nums1), len(nums2) lo, hi = 0, m
if len(nums1) > len(nums2):
nums1, nums2 = nums2, nums1When the searched array is longer than half the total, some cuts give a negative j. On [1, 2, 3, 4, 5, 6, 7] and [8] the search tries i = 5, so j = -1, and Python's nums2[j - 1] quietly reads from the end of the array and the result is 5.5 instead of 4.5. C++ and Java read out of bounds.
Averaging with integer division
return (max(left1, left2) + min(right1, right2)) / 2;
return (max(left1, left2) + (double) min(right1, right2)) / 2.0;
In C++ and Java, dividing two ints drops the fraction. On [1, 2] and [3, 4] the median is 2.5, but integer division returns 2.
Leaving the extra value on the right
half = (m + n) // 2
half = (m + n + 1) // 2
With an odd total, the middle value then lands on the right side, so max(left1, left2) is one place too early. On [1, 3] and [2] this returns 1 instead of 2.
Edge cases
[] and [1]After the swap the empty array is nums1, so the only cut is i = 0 and both of its borders are infinite. The checks pass at once and the median comes from nums2 alone.
Complexity
min(m, n) + 1 possible cuts. Only a few indexes and border values are stored.Median of Two Sorted Arrays FAQ
How is this related to the k-th smallest element of two sorted arrays?
The median is the k-th smallest value with k = (m + n + 1) / 2, averaged with the next one when the total is even. A k-th element search compares the k/2-th value of each array and throws away the smaller side's first k/2 values, which runs in O(log(m + n)). The cut search here does the same job without recursion.
Does it still work when the arrays share values?
Yes. The checks use <=, so equal values on both sides of a cut are allowed. On [1, 1] and [1, 1] the first cut tried already passes and the median is 1.