You are given two sorted arrays named nums1
and nums2
of length m
and n
respectively, you have to return the median of these two sorted arrays.
The total run time complexity should not be more than O(log (m+n))
.
Example 1:
Input: nums1 = [1,3], nums2 = [2] Output: 2.00000 Explanation: integrated array = [1,2,3] and median is 2.
Example 2:
Input: nums1 = [1,2], nums2 = [3,4] Output: 2.50000 Explanation: integrated array = [1,2,3,4] and median is (2 + 3) / 2 = 2.5.
Constraints:
nums1.size() == m
nums2.size() == n
0 <= m <= 1000
0 <= n <= 1000
1 <= m + n <= 2000
-106 <= nums1[i], nums2[i] <= 106
Approach :
We will do a binary search in one of the arrays which has a minimum size between the two.
Firstly, calculate the median position with (n+1)/2. Point two-pointer, say low and high, equal to 0, and the size of the array on which we are applying binary search respectively. Find the partition of the array.
Check that the left half of the array has an equal element to the current position of the median. If the condition is false, take some elements from the right half (second array ). Now, check if the partitioning is valid. This is only when l1<=r2 and l2<=r1. If valid, return max(l1,l2)(when odd number of elements present) else return (max(l1,l2)+min(r1,r2))/2.
If partitioning is not valid, move ranges. When l1>r2, move left and perform the above operations again. When l2>r2, move right and perform the above operations.