PracticeNeetCode ↗LeetCode ↗
Given two sorted arrays nums1 and nums2 of sizes m and n, return the median of the combined data — in O(log(min(m, n))) time.
nums1 is the smaller array, swapping if needed, since the binary search runs over it.nums1; the matching partition index in nums2 follows from how many elements the combined left half needs.nums1, depending on which boundary comparison failed.Time: O(log(min(m, n))) — Space: O(1)
def findMedianSortedArrays(nums1: list[int], nums2: list[int]) -> float:
if len(nums1) > len(nums2):
nums1, nums2 = nums2, nums1
m, n = len(nums1), len(nums2)
left, right = 0, m
half = (m + n + 1) // 2
while left <= right:
i = left + (right - left) // 2
j = half - i
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 == 0:
return (max(left1, left2) + min(right1, right2)) / 2
return float(max(left1, left2))
elif left1 > right2:
right = i - 1
else:
left = i + 1
return 0.0How the solution above works, piece by piece.
nums1 is the shorter array; the binary search runs over its possible cut positions 0..m, which is O(log(min(m, n))).half = (m + n + 1) // 2 is how many elements belong on the left. Choosing cut i in nums1 forces j = half - i in nums2.left1, right1, left2, right2 are the values on each side of the two cuts, with ±∞ standing in when a cut is at an edge.left1 <= right2 and left2 <= right1. Then the median is max(left) for an odd total, or the average of max(left) and min(right) for an even total.left1 > right2, too much of nums1 is on the left: move the cut left. Otherwise move it right.Running it on nums1 = [1, 3], nums2 = [2]:
nums1 is the shorter array ([2]). It looks for a cut through both arrays with 2 elements on the left and every left value ≤ every right value. The median then comes straight from the values next to the cut.