Given two sorted arrays nums1
and nums2
of size m
and n
respectively, return the median of the two sorted arrays.
The overall run time complexity should be O(log (m+n))
.
Example 1:
Input: nums1 = [1,3], nums2 = [2] Output: 2.00000 Explanation: merged array = [1,2,3] and median is 2.
Example 2:
Input: nums1 = [1,2], nums2 = [3,4] Output: 2.50000 Explanation: merged array = [1,2,3,4] and median is (2 + 3) / 2 = 2.5.
Constraints:
nums1.length == m
nums2.length == n
0 <= m <= 1000
0 <= n <= 1000
1 <= m + n <= 2000
-106 <= nums1[i], nums2[i] <= 106
This problem challenges us to find the median of two sorted arrays with a time complexity of O(log(m+n)), where 'm' and 'n' are the lengths of the input arrays. A naive approach of merging and sorting would be O(m+n), exceeding the requirement. Therefore, a divide and conquer strategy using binary search is necessary.
Core Idea:
The solution leverages a recursive helper function f(i, j, k)
to efficiently find the k-th smallest element in the combined arrays. This function cleverly avoids explicitly merging the arrays, thus achieving the logarithmic time complexity.
f(i, j, k)
: This function searches for the k-th smallest element, starting from index i
in nums1
and index j
in nums2
.
Base Cases:
i
reaches the end of nums1
, the k-th smallest element is found directly in nums2
(starting from j
).j
reaches the end of nums2
, the element is in nums1
(starting from i
).k
is 1, the k-th smallest is simply the minimum of the current elements in nums1
and nums2
.Recursive Step:
k
in half (p = k // 2
). We then identify potential k-th smallest candidates: x
from nums1
and y
from nums2
at the positions i + p - 1
and j + p - 1
, respectively. If either index is out of bounds, we use a large placeholder value (like 1 << 30
) to represent infinity, guaranteeing that it won't be the k-th smallest.x
and y
:
x <= y
, x
cannot be the k-th smallest, so we recursively call f
excluding the elements from i
to i + p
in nums1
.x > y
, y
cannot be the k-th smallest, so we recursively call f
excluding the elements from j
to j + p
in nums2
.Median Calculation:
The median is found by calling f
twice: once to get the floor((m+n+1)/2)th smallest and again for the floor((m+n+2)/2)th smallest. The average of these two values is the median.
Time Complexity Analysis:
Each recursive call to f
effectively halves the search space (k
). This is akin to a binary search, resulting in O(log(m+n)) time complexity.
Space Complexity Analysis:
The space complexity is determined by the recursive call stack. In the worst case, the depth of the recursion is O(log(m+n)), leading to O(log(m+n)) space complexity.
Code Examples (Python):
import sys
class Solution:
def findMedianSortedArrays(self, nums1: list[int], nums2: list[int]) -> float:
m, n = len(nums1), len(nums2)
def f(i: int, j: int, k: int) -> int:
if i >= m:
return nums2[j + k - 1]
if j >= n:
return nums1[i + k - 1]
if k == 1:
return min(nums1[i], nums2[j])
p = k // 2
x = nums1[i + p - 1] if i + p - 1 < m else float('inf')
y = nums2[j + p - 1] if j + p - 1 < n else float('inf')
return f(i + p, j, k - p) if x <= y else f(i, j + p, k - p)
a = f(0, 0, (m + n + 1) // 2)
b = f(0, 0, (m + n + 2) // 2)
return (a + b) / 2
This Python code directly reflects the algorithm described above. Note the use of float('inf')
to handle cases where array indices go out of bounds. The other languages provided follow a very similar structure and logic.