Median of Two Sorted Arrays Problem LeetCode

Median of Two Sorted Arrays Problem in LeetCode

1. Ensure that nums1 is the smaller array. If not, swap nums1 and nums2.

2. Initialize low and high variables for binary search on the smaller array nums1. The binary search is performed on the smaller array because it allows for determining the partition point in logarithmic time complexity.

3. Use binary search to find a partition point (partitionX) in the smaller array nums1. The partition point is chosen such that the number of elements on the left side of the combined arrays is equal to the number of elements on the right side.

4. Calculate the corresponding partition point in the larger array nums2 (partitionY). The total number of elements on the left side is (x + y + 1) / 2 - partitionX, where x and y are the lengths of nums1 and nums2, respectively.

5. Determine the elements on both sides of the partition in both arrays (maxX, maxY, minX, and minY).

6. Check if the current partition is valid, i.e., maxX is less than or equal to minY and maxY is less than or equal to minX.

7. If the partition is valid, calculate the median based on whether the total number of elements is even or odd.

8. If the partition is not valid, adjust the search range based on whether maxX is greater than minY or maxY is greater than minX.

9. Repeat the process until a valid partition is found.

10. If no valid partition is found, throw an IllegalArgumentException indicating that the input arrays are not sorted.

Click for My Solution in Github
Leetcode Menu