Example 1
- Input
- nums1 = [1,3], nums2 = [2]
- Output
- 2.00000
The merged array is [1, 2, 3] and its middle value is 2.
Given two sorted arrays, return the median of their combined elements without merging them. Binary searching the split point in the smaller array balances both halves and reads the median off the four border values.
Given two sorted arrays nums1 and nums2 of size m and n respectively, return the median of the two sorted arrays.
The median is the middle value of the merged order, or the average of the two middle values when the combined length is even. The overall run time complexity should be , which rules out merging both arrays.
nums1.length == mnums2.length == n0 <= m <= 10000 <= n <= 10001 <= m + n <= 2000-10^6 <= nums1[i], nums2[i] <= 10^6The merged array is [1, 2, 3] and its middle value is 2.
The merged array is [1, 2, 3, 4] and the median is (2 + 3) / 2 = 2.5.
One input is empty and the combined length is the minimum allowed, one. The only element is 7, so it is the median; the empty input contributes no actual border values.
The combined order is [-1000000, 2, 2, 2, 1000000, 1000000]. Positions 2 and 3 both contain 2, so their average is 2. Equal border values form a valid cut, even with negative and maximum-bound values elsewhere.
A median separates the smaller half of the values from the larger half. A partition is a cut between elements, and its position counts how many elements are on the left. For [1, 3] and [2], cuts after 1 and 2 give a left half containing [1, 2] and a right half containing [3]. The left half holds one extra element for an odd total, so its largest value, 2, is the median. Sorted inputs let us verify a cut using only the values beside it instead of building the full merged order.
Reveal Merge Then Median: intuition, complexity, and code
[] and [7] return 7, while [] and [1, 2] return 1.5. Both empty is excluded by the combined-length constraint.[-1000000] and [1000000], the median is 0; sentinel values must not replace a real middle value.0 as a missing-border stand-in instead of infinities, which corrupts comparisons on negative inputs.0 through m, and the last value on the left is at i - 1.total // 2 for the left size with the shown odd-case return; this code needs (total + 1) // 2 so the extra value is on the left.For order statistics over sorted inputs, binary search the partition point rather than the value: a valid split exposes the answer in its borders.