Median of Two Sorted Arrays Problem
Description
LeetCode Problem 4. Given two sorted arrays nums1 and nums2 of size m and n respectively, return the median of the two sorted arrays.
Example:
Input: nums1 = [1,3], nums2 = [2]
Output: 2.00000
Explanation: merged array = [1,2,3] and median is 2.
Input: num1 = [1,2], nums2 = [3,4]
Output: 2.50000
Explanation: merged array = [1,2,3,4] and median is (2+3)/2 = 2.5.
Solution
Approach: Binary Search on the Partition
Merging the two arrays and taking the middle works in O(m + n). We can do better by never building the merged array: the median only depends on where the merged array is cut in half.
Split the merged array into a left half of half = (m + n + 1) / 2 elements and a right half. The left half is made of the first i elements of nums1 and the first j = half - i elements of nums2. So choosing i decides everything. With
left1 = nums1[i-1],right1 = nums1[i],left2 = nums2[j-1],right2 = nums2[j],
the cut is correct exactly when left1 <= right2 and left2 <= right1: every element on the left is no larger than every element on the right.
Binary search for i in [0, m], where nums1 is the shorter array (swap them first, so j never goes out of range):
- If
left1 > right2, we took too many fromnums1: search smalleri. - If
left2 > right1, we took too few: search largeri. - Otherwise the cut is correct. If
m + nis odd, the median ismax(left1, left2)(the left half has the extra element). If even, it is the average ofmax(left1, left2)andmin(right1, right2).
When i or j is 0 or at the end of its array, the missing neighbor does not exist. Use negative infinity for a missing left value and positive infinity for a missing right value, so the comparisons still hold. This also handles an empty array.
Complexity: O(log(min(m, n))) time and O(1) space, where m and n are the lengths of nums1 and nums2.
class Solution:
def findMedianSortedArrays(self, 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)
low, high = 0, m
while low <= high:
i = (low + high) // 2 # take nums1[:i] into the left half
j = half - i # and nums2[:j]
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:
# Every element on the left is <= every element on the right.
if (m + n) % 2 == 1:
return float(max(left1, left2))
return (max(left1, left2) + min(right1, right2)) / 2
if left1 > right2:
high = i - 1 # took too many from nums1
else:
low = i + 1 # took too few from nums1
return 0.0 # never reached for valid input
Now write it from memory
Close the write-up and solve it yourself against the tests.