Median of Two Sorted Arrays
Master this topic with zero to advance depth.
Median of Two Sorted Arrays
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 .
Examples
Level I: Merge and Find
Intuition
Use the merge step of merge sort to combine the two arrays into one sorted array. Then find the middle element(s).
Detailed Dry Run
nums1 = [1,3], nums2 = [2] Merged: [1,2,3]. n=3. Median: Index 1 (Value 2).
Level II: Recursive K-th Element
Intuition
Find the -th smallest element in two sorted arrays by comparing the middle elements of each array (divided by 2 at each step).
Detailed Dry Run
Find 5th element in [1,3,5,...] and [2,4,6,...]. Compare 2nd elements...
Level III: Optimal (Binary Search on Partitions)
Intuition
We can binary search for the correct partition point in the smaller array. A partition is correct if all elements on the left side are smaller than all elements on the right side.
Detailed Dry Run
nums1 = [1,3], nums2 = [2]
- BS on nums1. Low=0, High=2. i=1. j = (2+1+1)/2 - 1 = 1.
- LeftA=1, RightA=3, LeftB=2, RightB=inf.
- LeftA <= RightB (1 <= inf) and LeftB <= RightA (2 <= 3). Correct!
- Median: max(1, 2) = 2.0.
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.