Tutorialspoint
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)
ArraysWiproSnowflake
Editorial

Login to view the detailed solution and explanation for this problem.

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.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

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

Steps to solve by this approach:

 Step 1: Ensure the first array is smaller than the second one for simplification.

 Step 2: Use binary search to find the correct partition in the smaller array.
 Step 3: Calculate the corresponding partition in the larger array.
 Step 4: Check if the partition is correct by comparing the max element of left half with min element of right half.
 Step 5: If partition is correct, calculate the median based on whether the total length is odd or even.
 Step 6: If partition is not correct, adjust the search range and try again.
 Step 7: Handle edge cases where one array might be empty or much smaller than the other.

Submitted Code :