Tutorialspoint
Problem
Solution
Submissions

Find Median of Two Sorted Arrays

Certification: Advanced Level Accuracy: 0% Submissions: 0 Points: 15

Write a C# program to implement the FindMedianSortedArrays(int[] nums1, int[] nums2) function that finds the median of two sorted arrays. The overall run time complexity should be O(log(m+n)) where m and n are the sizes of the two arrays.

Example 1
  • Input: nums1 = [1, 3], nums2 = [2]
  • Output: 2.00000
  • Explanation:
    • Merged array = [1, 2, 3], median is 2.
Example 2
  • Input: nums1 = [1, 2], nums2 = [3, 4]
  • Output: 2.50000
  • Explanation:
    • Merged array = [1, 2, 3, 4], median is (2 + 3) / 2 = 2.5.
Constraints
  • nums1.length, nums2.length >= 0
  • nums1.length + nums2.length >= 1
  • nums1[i], nums2[i] can be any integer (including negatives)
  • Both arrays are sorted in non-decreasing order
  • Time Complexity: O(log(min(m, n)))
  • Space Complexity: O(1)
ArraysFacebookPwC
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 - this would result in O(m+n) time complexity
  • Use binary search on the smaller array to find the correct partition
  • Ensure that all elements on the left side are less than or equal to elements on the right side
  • Handle odd and even length cases separately for calculating the median
  • Be careful with edge cases like empty arrays

Steps to solve by this approach:

 Step 1: Ensure the first array is smaller than the second for optimization (binary search on the smaller array).
 Step 2: Define a binary search space on the smaller array from 0 to its length.
 Step 3: Calculate the partition point in the first array and determine the corresponding partition in the second array.
 Step 4: Find the elements around the partition points in both arrays (maxX, minX, maxY, minY).
 Step 5: Check if the partition is correct (maxX ≤ minY and maxY ≤ minX).
 Step 6: If the partition is correct, calculate and return the median based on whether the total length is odd or even.
 Step 7: If the partition is not correct, adjust the binary search space and continue.

Submitted Code :