Solution Code
def findMedianSortedArrays(nums1, nums2):
if len(nums1) > len(nums2):
nums1, nums2 = nums2, nums1
m, n = len(nums1), len(nums2)
low, high = 0, m
while low <= high:
i = (low + high) // 2
j = (m + n + 1) // 2 - i
left1 = float('-inf') if i == 0 else nums1[i-1]
left2 = float('-inf') if j == 0 else nums2[j-1]
maxLeft = max(left1, left2)
right1 = float('inf') if i == m else nums1[i]
right2 = float('inf') if j == n else nums2[j]
minRight = min(right1, right2)
if maxLeft <= minRight:
if (m + n) % 2 == 0:
return (maxLeft + minRight) / 2
else:
return maxLeft
else:
if i == 0 or (j != 0 and nums2[j-1] > nums1[i-1]):
low = i + 1
else:
high = i - 1
return 0 # should not reach here if input is correct
# Example usage:
nums1 = [1, 3]
nums2 = [2]
print(findMedianSortedArrays(nums1, nums2)) # Output: 2.0
nums1 = [1, 2]
nums2 = [3, 4]
print(findMedianSortedArrays(nums1, nums2)) # Output: 2.5
Explanation
The algorithm works by performing a binary search on the smaller array to find the correct partition such that the left half's maximum is less than or equal to the right half's minimum. This ensures that the combined left half is less than or equal to the combined right half, which is the property needed to find the median. The median is then calculated based on whether the total number of elements is odd or even. The binary search ensures that the solution is found in logarithmic time relative to the size of the smaller array.
The median of the two sorted arrays is found by ensuring that the left partition's maximum is less than or equal to the right partition's minimum, and then computing the median based on the total number of elements. This approach efficiently finds the median in O(log(min(m, n))) time.