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)).
Input: nums1 = [1,3], nums2 = [2]
Output: 2.00000
Explanation: merged array = [1,2,3] and median is 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.
The brute force approach of merging arrays takes O(m+n). To achieve O(log(m+n)), we use binary search on partition position.
Key Insight: The median divides an array into two equal halves. For two arrays, we need to find a partition such that:
We binary search on the smaller array to find the correct partition.
This is Advanced Binary Search (Partition-based) with:
Ensure nums1 is smaller: If m > n, swap arrays (search on smaller)
Binary Search on Partition:
left = 0, right = mCheck Valid Partition:
maxLeft1 = largest element in left half of nums1minRight1 = smallest element in right half of nums1maxLeft2, minRight2 = same for nums2maxLeft1 ≤ minRight2 AND maxLeft2 ≤ minRight1Calculate Median:
max(maxLeft1, maxLeft2)(max(maxLeft1, maxLeft2) + min(minRight1, minRight2)) / 2Adjust Search:
maxLeft1 > minRight2: Move left (partition1 too large)Time Complexity: O(log min(m, n))
Space Complexity: O(1)
1class Solution {
2 public double findMedianSortedArrays(int[] nums1, int[] nums2) {
3 // Ensure nums1 is the smaller array
4 if (nums1.length > nums2.length) {
5 return findMedianSortedArrays(nums2, nums1);
6 }
7
8 int m = nums1.length;
9 int n = nums2.length;
10 int left = 0;
11 int right = m;
12
13 while (left <= right) {
14 int partition1 = (left + right) / 2;
15 int partition2 = (m + n + 1) / 2 - partition1;
16
17 // Handle edge cases for partition boundaries
18 int maxLeft1 = (partition1 == 0) ? Integer.MIN_VALUE : nums1[partition1 - 1];
19 int minRight1 = (partition1 == m) ? Integer.MAX_VALUE : nums1[partition1];
20
21 int maxLeft2 = (partition2 == 0) ? Integer.MIN_VALUE : nums2[partition2 - 1];
22 int minRight2 = (partition2 == n) ? Integer.MAX_VALUE : nums2[partition2];
23
24 // Check if we found the correct partition
25 if (maxLeft1 <= minRight2 && maxLeft2 <= minRight1) {
26 // Found correct partition
27 if ((m + n) % 2 == 0) {
28 return (Math.max(maxLeft1, maxLeft2) + Math.min(minRight1, minRight2)) / 2.0;
29 } else {
30 return Math.max(maxLeft1, maxLeft2);
31 }
32 } else if (maxLeft1 > minRight2) {
33 // partition1 is too large, move left
34 right = partition1 - 1;
35 } else {
36 // partition1 is too small, move right
37 left = partition1 + 1;
38 }
39 }
40
41 throw new IllegalArgumentException("Input arrays are not sorted");
42 }
43}
44