
Problem
Solution
Submissions
Median of Two Sorted Arrays
Certification: Advanced Level
Accuracy: 17.65%
Submissions: 17
Points: 12
Write a Java program to find the median of two sorted arrays of different sizes. The median is the middle value of a set of numbers arranged in order. If the set has an even number of elements, the median is the average of the two middle values.
Example 1
- Input: nums1 = [1, 3], nums2 = [2]
- Output: 2.0
- Explanation:
- Merge the two arrays: [1, 2, 3].
- The merged array has odd length (3), so the median is the middle element, which is 2.0.
Example 2
- Input: nums1 = [1, 2], nums2 = [3, 4]
- Output: 2.5
- Explanation:
- Merge the two arrays: [1, 2, 3, 4].
- The merged array has even length (4), so the median is the average of the two middle elements: (2 + 3) / 2 = 2.5.
Constraints
- nums1.length + nums2.length >= 1
- nums1.length, nums2.length <= 1000
- -10^6 <= nums1[i], nums2[i] <= 10^6
- Both nums1 and nums2 are sorted in non-decreasing order
- Time Complexity: O(log(m+n)) where m and n are the sizes of the arrays
- 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
- Do not merge the arrays as it would result in O(m+n) time complexity
- Instead, use binary search to find the correct partition
- Partition both arrays such that the left half elements are less than or equal to right half elements
- Calculate the median using the maximum of left halves and minimum of right halves
- Handle odd and even total lengths separately
- Be careful about edge cases when one array is empty or much smaller than the other