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 O(\log(m+n)).
Visual Representation
nums1: [1, 3], nums2: [2]
Merged Sorted View:
[ 1, 2, 3 ]
^
Median = 2.0
Partition View (Optimal):
nums1: [ 1 | 3 ]
nums2: [ 2 | ]
Left Side: {1, 2}, Right Side: {3}
Median = Max(Left) = 2.0Examples
merged array = [1,2,3] and median is 2.
Level I: Brute Force (Merge Sort Style)
Intuition
Merge the two sorted arrays into a single sorted array and find the middle element(s).
Use the merge step from Merge Sort to combine the two arrays into one of size m+n. Calculate the median from the result.
Detailed Dry Run
nums1 = [1, 3], nums2 = [2]
- Combined array length = 3.
- Merge: i=0, j=0. nums1[0] < nums2[0] (1 < 2), merged = [1], i=1.
- i=1, j=0. nums2[0] < nums1[1] (2 < 3), merged = [1, 2], j=1.
- i=1, j=1. nums1[1] = 3, merged = [1, 2, 3], i=2.
- Median = merged[3/2] = merged[1] = 2.0.
⚠️ Common Pitfalls & Tips
Violates the O(log(M+N)) time requirement. Uses O(M+N) space.
Level II: Better (Two Pointers - Merge Part Only)
Intuition
Since both arrays are already sorted, we can use the merge step of Merge Sort to combine them in O(M+N). We don't even need to store the whole combined array; we only need to keep track of the middle elements.
Iterate through both arrays using two pointers, keeping track of the values seen. Stop when we reach the middle index (or indices if even).
Detailed Dry Run
Input: [1, 3], [2]
- Total size 3, Median index 1.
- Pointers:
i=0, j=0. Compare1and2.1is smaller.count=0, val=1, i=1. - Compare
3and2.2is smaller.count=1, val=2, j=1. - Median is
2.
⚠️ Common Pitfalls & Tips
O(M+N) is good but the problem asks for O(log(M+N)).
Level III: Optimal (Binary Search on Partitions)
Intuition
Instead of merging, we can partition the two arrays into two halves (left and right) such that the left half contains half of the elements and all elements in the left half are <= all elements in the right half.
Binary search on the smaller array to find a partition. For array A (smaller) at midA, and array B at midB = (total+1)/2 - midA, checking if A[midA-1] <= B[midB] and B[midB-1] <= A[midA].
Detailed Dry Run
Input: nums1 = [1,3], nums2 = [2]
Total elements = 3. Target partition size for left half = (3+1)/2 = 2.
-
Assume
nums1is the smaller array (x=2, y=1). -
Binary search
partitionXinnums1fromlow=0tohigh=2.-
Try
partitionX = 1(mid of 0,2).partitionY = (2+1+1)/2 - 1 = 2 - 1 = 1.maxLeftX = nums1[0] = 1minRightX = nums1[1] = 3maxLeftY = nums2[0] = 2minRightY = (partitionY == y) ? Integer.MAX_VALUE : nums2[partitionY]->nums2[1]is out of bounds, sominRightY = Infinity.
-
Check conditions:
maxLeftX <= minRightY(1 <= Infinity) -> True.maxLeftY <= minRightX(2 <= 3) -> True. -
Conditions met! Total elements (3) is odd. Median =
max(maxLeftX, maxLeftY) = max(1, 2) = 2.0.
-
⚠️ Common Pitfalls & Tips
Be careful with the partition logic and even/odd total counts. Binary search must be on the smaller array for O(log(min(M,N))).
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.