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
Median of Two Sorted Arrays: Binary Search ApproachStep 1: Partition ArraysArray A: [1, 3, 8, 9, 15] → Left: [1] | Right: [3, 8, 9, 15]Array B: [7, 11, 18, 19, 21, 25] → Left: [7, 11, 18, 19] | Right: [21, 25]Equal partition sizes: 5 elements on each sideStep 2: Validate PartitionLeft max: max(1, 19) = 19, Right min: min(3, 21) = 319 > 3: Invalid partition! Adjust binary search boundsStep 3: Find Valid PartitionAfter binary search: Left max ≤ Right minMedian = (Left max + Right min) / 2 for even total lengthO(log n)🎯 Key Insight: Binary search finds the perfect split point without merging arrays
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.
Asked in
Google 89 Amazon 67 Microsoft 45 Apple 34 Facebook 56
987.7K Views
High Frequency
~25 min Avg. Time
15.4K 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