
Problem
Solution
Submissions
Find Median of Two Sorted Arrays
Certification: Advanced Level
Accuracy: 100%
Submissions: 2
Points: 15
Write a program to find the median of two sorted arrays. The median is the middle value of a set of numbers. If the set has an odd number of elements, the median is the middle element. If the set has an even number of elements, the median is the average of the two middle elements.
Example 1
- Input: nums1 = [1, 3], nums2 = [2]
- Output: 2.0
- Explanation:
- Step 1: Merged array = [1, 2, 3]
- Step 2: Median is the middle element (2.0)
Example 2
- Input: nums1 = [1, 2], nums2 = [3, 4]
- Output: 2.5
- Explanation:
- Step 1: Merged array = [1, 2, 3, 4]
- Step 2: Median is average of middle two elements (2 + 3)/2 = 2.5
Constraints
- nums1.length == m
- nums2.length == n
- 0 ≤ m ≤ 1000
- 0 ≤ n ≤ 1000
- 1 ≤ m + n ≤ 2000
- -10^6 ≤ nums1[i], nums2[i] ≤ 10^6
- Time Complexity: O(log(m+n))
- Space Complexity: O(1)
Editorial
My Submissions
All Solutions
Lang | Status | Date | Code |
---|---|---|---|
You do not have any submissions for this problem. |
User | Lang | Status | Date | Code |
---|---|---|---|---|
No submissions found. |
Solution Hints
- A naive approach would be to merge the arrays and find the median, but that would be O(m+n)
- Use binary search to find a partition point in one array that correctly divides the elements
- The partition in the second array is computed based on the first partition
- Check if the partitions are correct by comparing the maximum of left parts and minimum of right parts
- Adjust the partition points until the correct median is found