Median of Two Sorted Arrays - Complete Solution Guide
Median of Two Sorted Arrays is LeetCode problem 4, a Hard level challenge. This complete guide provides step-by-step explanations, multiple solution approaches, and optimized code in python3, java, cpp, c.
Problem Statement
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)) . Example 1: Input: nums1 = [1,3], nums2 = [2] Output: 2.00000 Explanation: merged array = [1,2,3] and median is 2. Example 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. Constraints: nums1.length == m nums2.length == n 0 <= m <= 1000 0 <= n <= 1000 1
Detailed Explanation
The problem requires finding the median of two sorted arrays, `nums1` and `nums2`. The median is the middle element (or the average of the two middle elements if the total number of elements is even) when the combined array is sorted. The crucial constraint is to achieve this with a time complexity of O(log(m+n)), where m and n are the lengths of the input arrays.
Solution Approach
The solution employs a binary search approach to find the optimal partition points in the two sorted arrays. By partitioning the arrays, the algorithm seeks to satisfy the condition where the maximum element on the left side of the partition in both arrays is less than or equal to the minimum element on the right side. This indicates that the elements are correctly 'merged' such that the median can be calculated. We perform binary search on the smaller array to optimize the search space.
Step-by-Step Algorithm
- Step 1: Ensure that `nums1` is the shorter array. If not, swap `nums1` and `nums2`.
- Step 2: Initialize `low` to 0 and `high` to the length of `nums1` (`m`). These represent the possible number of elements to take from `nums1` in the left partition.
- Step 3: Calculate `half_len` as `(m + n + 1) // 2`. This represents the number of elements that should be in the left partition of the merged array.
- Step 4: Perform binary search within the range `[low, high]`. In each iteration:
- Step 5: Calculate `partition1` as `(low + high) // 2`. This is the number of elements taken from `nums1` in the left partition.
- Step 6: Calculate `partition2` as `half_len - partition1`. This ensures that the total number of elements in the left partitions of both arrays is `half_len`.
- Step 7: Determine `maxLeft1`, `minRight1`, `maxLeft2`, and `minRight2`. These are the maximum element to the left and the minimum element to the right of the partitions in each array. Handle edge cases where partitions are at the beginning or end of the arrays by assigning negative or positive infinity respectively.
- Step 8: Check if `maxLeft1 <= minRight2` and `maxLeft2 <= minRight1`. If this condition is met, the correct partition is found.
- Step 9: If the condition in Step 8 is met, check if the total length of both arrays is even or odd.
- Step 10: If the total length is even, the median is the average of the maximum of `maxLeft1` and `maxLeft2` and the minimum of `minRight1` and `minRight2`.
- Step 11: If the total length is odd, the median is the maximum of `maxLeft1` and `maxLeft2`.
- Step 12: If `maxLeft1 > minRight2`, move the `high` pointer to `partition1 - 1` to search in the left half.
- Step 13: Otherwise, move the `low` pointer to `partition1 + 1` to search in the right half.
- Step 14: Repeat steps 4-13 until the correct partition is found.
Key Insights
- Insight 1: Direct merging and sorting would result in O(m+n) time complexity, violating the logarithmic time constraint. Binary search is essential.
- Insight 2: The problem can be reframed as finding the correct partition points in both arrays such that all elements to the left of the partitions are smaller than all elements to the right.
- Insight 3: Swapping arrays to ensure that binary search is performed on the smaller array guarantees a tighter upper bound for the search, improving efficiency.
Complexity Analysis
Time Complexity: O(log(min(m,n)))
Space Complexity: O(1)
Topics
This problem involves: Array, Binary Search, Divide and Conquer.
Companies
Asked at: Accenture, Adobe, Akamai, Amazon, Apple, Autodesk, Bloomberg, Capgemini, Citadel, Cognizant, DE Shaw, Dropbox, Flipkart, Goldman Sachs, Google, IBM, Infosys, Intuit, LinkedIn, Meta, Microsoft, Oracle, Palo Alto Networks, PayPal, PornHub, Pwc, Rippling, ServiceNow, Snap, Swiggy, TikTok, Uber, VMware, Visa, Walmart Labs, Wipro, Wix, Yahoo, Yandex, Zenefits, Zoho, eBay.