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 INPUT nums1 (m=2) 1 3 idx 0 idx 1 nums2 (n=1) 2 idx 0 Sorted arrays to merge: [1, 3] + [2] Total: m + n = 3 elements Median position: (3+1)/2 = 2 ALGORITHM STEPS 1 Binary Search Setup Pick smaller array (nums1) for partition search 2 Find Partition Points partX=1, partY=1 Left half = Right half [1] | [3] [2] | - 3 Validate Partition maxLeft1(1) <= minRight2 maxLeft2(2) <= minRight1(3) 4 Calculate Median Odd total: max(left) max(1, 2) = 2 Time: O(log(min(m,n))) FINAL RESULT Merged Sorted Array 1 2 3 MEDIAN Output: 2.0 OK Middle element of 3 sorted elements Key Insight: Binary search on the smaller array to find the correct partition. The partition divides both arrays such that all elements on the left are smaller than all elements on the right. For odd total elements, the median is max(leftPart). This achieves O(log(min(m,n))) time complexity instead of O(m+n) merge approach. TutorialsPoint - Median of Two Sorted Arrays | Optimal Solution (Binary Search)
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