Tutorialspoint
Problem
Solution
Submissions

Median of Two Sorted Arrays

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

Write a C program to find the median of two sorted arrays. The overall run time complexity should be O(log (m+n)). Given two sorted arrays nums1 and nums2 of size m and n respectively, return the median of the two sorted arrays.

Example 1
  • Input: nums1 = [1,3], nums2 = [2]
  • Output: 2.00000
  • Explanation:
    • Merged array = [1,2,3].
    • The median is 2 (middle element).
    • Therefore, the median is 2.00000
Example 2
  • Input: nums1 = [1,2], nums2 = [3,4]
  • Output: 2.50000
  • Explanation:
    • Merged array = [1,2,3,4].
    • The median is (2 + 3) / 2 = 2.5 (average of two middle elements).
    • Therefore, the median is 2.50000
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(min(m,n)))
  • Space Complexity: O(1)
ArraysAlgorithmsHCL TechnologiesDropbox
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

  • Use binary search on the smaller array to partition both arrays
  • Ensure that elements on the left side are smaller than elements on the right side
  • Find the correct partition where left_max ≤ right_min for both arrays
  • If total length is odd, median is the maximum of left elements
  • If total length is even, median is the average of maximum left and minimum right elements

Steps to solve by this approach:

 Step 1: Ensure nums1 is the smaller array to optimize binary search
 Step 2: Initialize binary search boundaries (low = 0, high = size of smaller array)
 Step 3: Calculate partition points for both arrays using binary search
 Step 4: Find maximum elements on left side and minimum elements on right side
 Step 5: Check if partition is valid (left_max ≤ right_min for both arrays)
 Step 6: If valid, calculate median based on total length (odd/even)
 Step 7: If not valid, adjust binary search boundaries and repeat

Submitted Code :