Median of Two Sorted Arrays - Problem

You are given two sorted arrays nums1 and nums2 of sizes m and n respectively. Your task is to find the median of the combined sorted array without actually merging the arrays.

The median is the middle value in a sorted list. If the list has an even number of elements, the median is the average of the two middle numbers.

Challenge: Can you solve this in O(log(m+n)) time complexity? This constraint makes the problem significantly more interesting as it rules out simple merging approaches.

Examples:

  • nums1 = [1,3], nums2 = [2] → Combined: [1,2,3] → Median: 2.0
  • nums1 = [1,2], nums2 = [3,4] → Combined: [1,2,3,4] → Median: (2+3)/2 = 2.5

Input & Output

example_1.py — Basic Case
$ Input: nums1 = [1,3], nums2 = [2]
Output: 2.00000
💡 Note: Merged array: [1,2,3]. The median is 2.
example_2.py — Even Length
$ Input: nums1 = [1,2], nums2 = [3,4]
Output: 2.50000
💡 Note: Merged array: [1,2,3,4]. The median is (2 + 3) / 2 = 2.5.
example_3.py — One Empty Array
$ Input: nums1 = [], nums2 = [1]
Output: 1.00000
💡 Note: Only nums2 has elements. The median is 1.

Visualization

Tap to expand
Perfect Partition Approachnums1 (smaller array)nums2 (larger array)13Cut i891571118Cut j1921LEFT HALF (5 elements)RIGHT HALF (6 elements)Validation Check:max(left) = max(3, 18) = 18min(right) = min(8, 19) = 818 > 8 ❌ Invalid! Try different partitionBinary search continues until valid partition found
Understanding the Visualization
1
Setup
We have two sorted arrays and want to partition them into left and right halves
2
Binary Search
Use binary search to try different partition points in the smaller array
3
Calculate Complement
For each partition point i in nums1, calculate corresponding point j in nums2
4
Validate
Check if max(left_elements) ≤ min(right_elements) across both arrays
5
Find Median
When valid partition found, median is at the boundary of left and right halves
Key Takeaway
🎯 Key Insight: Instead of finding the median directly, find the perfect partition where all left elements ≤ all right elements. The median lies exactly at this boundary!

Time & Space Complexity

Time Complexity
⏱️
O(log(min(m,n)))

Binary search is performed on the smaller array, giving logarithmic time complexity

n
2n
Linearithmic
Space Complexity
O(1)

Only using constant extra space for variables

n
2n
Linear Space

Constraints

  • nums1.length == m
  • nums2.length == n
  • 0 ≤ m ≤ 1000
  • 0 ≤ n ≤ 1000
  • 1 ≤ m + n ≤ 2000
  • -106 ≤ nums1[i], nums2[i] ≤ 106
  • Follow-up: The overall run time complexity should be O(log (m+n))
Asked in
Google 45 Amazon 38 Meta 32 Microsoft 28 Apple 22 ByteDance 18
52.4K Views
Very High Frequency
~25 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen