Median of Two Sorted Arrays
You are given two sorted arrays, nums1
and nums2
, where nums1
has size m
and nums2
has size n
. Your task is to find the median of the two sorted arrays.
If possible, the overall run time complexity should be O(log(min(m, n))
).
Function Signature:
from typing import List
def find_median_sorted_arrays(nums1: List[int], nums2: List[int]) -> float:
"""
Find the median of the two sorted arrays.
Parameters:
- nums1: A sorted array of integers.
- nums2: A sorted array of integers.
Returns:
- float: The median of the two sorted arrays.
"""
# Your code here
Example:
result = find_median_sorted_arrays([1, 3], [2])
print(result)
assert result == 2.0, "The result should be 2.0"
# Explanation: The merged array is [1, 2, 3], and the median is 2.
result = find_median_sorted_arrays([1, 2], [3, 4])
print(result)
assert result == 2.5, "The result should be 2.5"
# Explanation: The merged array is [1, 2, 3, 4], and the median is (2 + 3) / 2 = 2.5.
result = find_median_sorted_arrays([1, 2], [10, 20])
print(result)
assert result == 6.0, "The result should be 2.5"
# Explanation: The merged array is [1, 2, 10, 20], and the median is (2 + 10) / 2 = 6.0.
result = find_median_sorted_arrays([0, 0], [0, 0])
print(result)
assert result == 0.0, "The result should be 0.0"
# Explanation: The merged array is [0, 0, 0, 0], and the median is 0.
result = find_median_sorted_arrays([], [1])
print(result)
assert result == 1.0, "The result should be 1.0"
# Explanation: The merged array is [1], and the median is 1.
Note:
- The input arrays
nums1
andnums2
are both sorted in ascending order. - If possible, the overall run time complexity should be O(
log(min(m, n))
).
Instructions:
- Write the
find_median_sorted_arrays
function to solve the problem. - Implement your solution in Python.
- Provide clear comments in your code.
- Discuss the time and space complexity of your solution.
As always, we’ll share our solution to this problem tomorrow. Stay tuned 😊