21-Median of Two Sorted Arrays
Last updated
Was this helpful?
Last updated
Was this helpful?
The problem can be found at the following link:
Calculate the sizes of nums1
and nums2
and store them in variables n
and m
, respectively.
Check if the size of nums1
is greater than the size of nums2
. If it is, swap the arrays to ensure that nums1
is the smaller array.
Calculate the total size of the combined array as size = n + m
.
Initialize variables low
and high
to 0 and n
, respectively. These variables will be used for binary search on the smaller array (nums1
) to find the partition point.
Calculate the left partition size as left = (n + m + 1) / 2
. This is because if the combined size is odd, you want the left partition to have one more element.
Perform a binary search within the range [low, high]
to find the partition point in nums1
. Use the mid1
and mid2
variables to partition nums1
and nums2
, respectively.
Calculate l1
, r1
, l2
, and r2
, which represent the elements to the left and right of the partition points in nums1
and nums2
.
Check if l1
is less than or equal to r2
and l2
is less than or equal to r1
. This condition ensures that you have found the correct partition points.
a. If the condition is met and size
is odd (size
is an odd number), return the maximum of l1
and l2
as the median.
b. If the condition is met and size
is even (size
is an even number), return the average of the maximum of l1
and l2
and the minimum of r1
and r2
as the median.
If the condition in step 8 is not met, adjust the binary search range (low
and high
) based on whether l1
is greater than r2
or l2
is greater than r1
. This adjustment ensures that you move the partition point in the correct direction.
Repeat the binary search until you find the correct partition points that satisfy the condition in step 8.
If the binary search does not find the correct partition points, return 0.0 as there might be an issue with the input arrays.
Time Complexity: O(log(min(n,m)))
Auxiliary Space Complexity: O(1)
For discussions, questions, or doubts related to this solution, please visit our . We welcome your input and aim to foster a collaborative learning environment.
If you find this solution helpful, consider supporting us by giving a ⭐ star
to the repository.