Median of Two Sorted Arrays - Problem
Given two sorted arrays nums1 and nums2 of size m and n respectively, return the median of the two sorted arrays.
The overall run time complexity should be O(log (m+n)).
Note: The median is the middle value in an ordered, integer list. If the size of the list is even, there is no middle value and the median is the mean of the two middle values.
Input & Output
Example 1 — Even Length
$
Input:
nums1 = [1,3], nums2 = [2]
›
Output:
2.0
💡 Note:
Merged array is [1,2,3] and median is 2.0
Example 2 — Odd Length
$
Input:
nums1 = [1,2], nums2 = [3,4]
›
Output:
2.5
💡 Note:
Merged array is [1,2,3,4] and median is (2 + 3) / 2 = 2.5
Example 3 — Single Element
$
Input:
nums1 = [], nums2 = [1]
›
Output:
1.0
💡 Note:
Merged array is [1] and median is 1.0
Constraints
- nums1.length == m
- nums2.length == n
- 0 ≤ m ≤ 1000
- 0 ≤ n ≤ 1000
- 1 ≤ m + n ≤ 2000
- -106 ≤ nums1[i], nums2[i] ≤ 106
Visualization
Tap to expand
Understanding the Visualization
1
Setup Binary Search
Search on the smaller array for efficiency
2
Find Partition Points
Calculate split positions for both arrays
3
Validate Partition
Check if max(left) ≤ min(right) for both arrays
4
Calculate Median
Use boundary values to get the median
Key Takeaway
🎯 Key Insight: The median divides all elements into two equal halves. By using binary search to find the right partition, we can achieve O(log(min(m,n))) time complexity without actually merging the arrays.
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code