Median of Two Sorted Arrays
Given two sorted arrays nums1 and nums2 of sizes m and n, return the median of all m + n values together.
The median is the middle value of the combined sorted list. When the total count is even, it's the average of the two middle values. Your solution must run in O(log(m + n)) time. The tests round your answer to 5 decimal places before comparing.
Example 1
Input: nums1 = [1, 3], nums2 = [2] Output: 2.0
Together the values are [1, 2, 3], and the middle one is 2.
Example 2
Input: nums1 = [1, 2], nums2 = [3, 4] Output: 2.5
The combined list [1, 2, 3, 4] has two middle values, so the median is (2 + 3) / 2.
Constraints
0 <= m, n <= 10001 <= m + n <= 2000-10^6 <= nums1[i], nums2[i] <= 10^6- Both arrays are sorted in non-decreasing order.
Approach
Merging both arrays and reading the middle takes O(m + n). The O(log) solution never builds the merged list. Instead, it searches for the split that divides all the values into a left half and a right half of equal size, with everything on the left no larger than everything on the right. The median then comes from the values right next to that split.
Make nums1 the shorter array. The left half needs half = (m + n + 1) // 2 values. If it takes i values from the front of nums1, it must take j = half - i from the front of nums2, so choosing i fixes the whole split. Call the last value taken from each array left1 and left2, and the first value left behind right1 and right2. Both arrays are sorted, so the split is valid exactly when left1 <= right2 and left2 <= right1.
If left1 > right2, the left half took too many from nums1, so search smaller i. Otherwise it took too few, so search larger i. Treat a missing neighbor at either end of an array as negative or positive infinity. Once the split is valid, the median is max(left1, left2) for an odd total, or the average of that and min(right1, right2) for an even total.
Steps
- Swap the arrays if needed so that
nums1is the shorter one. - Set
half = (m + n + 1) // 2and binary searchibetween0andm. - Set
j = half - iand readleft1,right1,left2andright2, using infinities past the ends. - If
left1 <= right2andleft2 <= right1, return the median from those four values. - If
left1 > right2, move the search left. Otherwise move it right.
from typing import List
def find_median_sorted_arrays(nums1: List[int], nums2: List[int]) -> float:
if len(nums1) > len(nums2):
nums1, nums2 = nums2, nums1 # binary search over the shorter array
m, n = len(nums1), len(nums2)
half = (m + n + 1) // 2 # size of the left half (gets the extra element when the total is odd)
lo, hi = 0, m
while lo <= hi:
i = (lo + hi) // 2 # elements of nums1 in the left half
j = half - i # elements of nums2 in the left half
left1 = nums1[i - 1] if i > 0 else float("-inf")
right1 = nums1[i] if i < m else float("inf")
left2 = nums2[j - 1] if j > 0 else float("-inf")
right2 = nums2[j] if j < n else float("inf")
if left1 <= right2 and left2 <= right1:
if (m + n) % 2:
return float(max(left1, left2))
return (max(left1, left2) + min(right1, right2)) / 2
if left1 > right2:
hi = i - 1 # took too many from nums1
else:
lo = i + 1 # took too few from nums1
raise ValueError("input arrays must be sorted")Complexity
- Time:
O(log(min(m, n))). The binary search runs over the shorter array. - Space:
O(1).
Common mistakes
- Binary searching over the longer array, which can make
jnegative or larger thann. - Forgetting the edges: when
i = 0there's noleft1, and wheni = mthere's noright1. - Using integer division for the even case and losing the
.5.
**public** **static** **double** findMedianSortedArrays_twopointers(**int**\[\] nums1, **int**\[\] nums2) { **int** n1 = nums1.length, n2 = nums2.length, i1 = 0, i2 = 0, totalLength = n1 + n2, mid = totalLength / 2; **boolean** isEven = totalLength % 2 == 0 ? **true** : **false**; List<Integer> mergedList = **new** ArrayList<>(); **while** (i1 < n1 || i2 < n2) { **int** num = -1; // if i2 reach end, use i1 **if** (i2 == n2) num = nums1\[i1++\]; // if i1 reach end, use i2 **else** **if** (i1 == n1) num = nums2\[i2++\]; // get smaller one **else** **if** (nums1\[i1\] >= nums2\[i2\]) num = nums2\[i2++\]; **else** **if** (nums1\[i1\] < nums2\[i2\]) num = nums1\[i1++\]; mergedList.add(num); } System.***out***.println("mergedList = " + mergedList); **return** isEven ? (**double**) (mergedList.get(mid - 1) + mergedList.get(mid)) / 2.0 : mergedList.get(mid); }