21-Median of Two Sorted Arrays
The problem can be found at the following link: Question Link
My Approach
Calculate the sizes of
nums1
andnums2
and store them in variablesn
andm
, respectively.Check if the size of
nums1
is greater than the size ofnums2
. If it is, swap the arrays to ensure thatnums1
is the smaller array.Calculate the total size of the combined array as
size = n + m
.Initialize variables
low
andhigh
to 0 andn
, 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 innums1
. Use themid1
andmid2
variables to partitionnums1
andnums2
, respectively.Calculate
l1
,r1
,l2
, andr2
, which represent the elements to the left and right of the partition points innums1
andnums2
.Check if
l1
is less than or equal tor2
andl2
is less than or equal tor1
. 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 ofl1
andl2
as the median.b. If the condition is met and
size
is even (size
is an even number), return the average of the maximum ofl1
andl2
and the minimum ofr1
andr2
as the median.If the condition in step 8 is not met, adjust the binary search range (
low
andhigh
) based on whetherl1
is greater thanr2
orl2
is greater thanr1
. 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 and Auxiliary Space Complexity
Time Complexity:
O(log(min(n,m)))
Auxiliary Space Complexity:
O(1)
Code (C++)
Contribution and Support
For discussions, questions, or doubts related to this solution, please visit our discussion section. 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 rishabhv12/Daily-Leetcode-Solution repository.
Last updated