Median of Two Sorted Arrays
Expert Answer & Key Takeaways
A complete guide to understanding and implementing Binary Search.
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
Input: nums1 = [1,3], nums2 = [2]
Output: 2.00000
Input: nums1 = [1,2], nums2 = [3,4]
Output: 2.50000
Approach 1
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).
⏱ $O(M + N)$💾 $O(M + N)$
Detailed Dry Run
nums1 = [1,3], nums2 = [2]
Merged: [1,2,3]. n=3. Median: Index 1 (Value 2).
Approach 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).
⏱ $O(\log(M+N))$💾 $O(\log(M+N))$ due to recursion stack.
Detailed Dry Run
Find 5th element in [1,3,5,...] and [2,4,6,...]. Compare 2nd elements...
Approach 3
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.
⏱ $O(\\log(\\min(M, N)))$💾 $O(1)$
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.
Course4All Technical Board
Verified ExpertSenior Software Engineers & Algorithmic Experts
Our DSA content is authored and reviewed by engineers from top tech firms to ensure optimal time and space complexity analysis.
Pattern: 2026 Ready
Updated: Weekly
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.