Tutorialspoint
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)
ArraysAlgorithmsAccentureDropbox
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

  • 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

Steps to solve by this approach:

 Step 1: Ensure the first array is the smaller one to minimize binary search operations.

 Step 2: Use binary search to find the partition point in the first array.
 Step 3: Calculate the corresponding partition point in the second array to ensure both sides have equal total elements.
 Step 4: Check if the partitions are correct by verifying that the maximum element on the left side of both arrays is less than or equal to the minimum element on the right side of both arrays.
 Step 5: If the partitions are correct, calculate the median based on whether the total number of elements is odd or even.

Submitted Code :