Median of Two Sorted Arrays
Hard
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)) or O(log(min(m, n))).
Imagine two separate stacks of graded exam papers, both already arranged from lowest score to highest score. You want to find the median score of all students combined without combining all papers into one massive pile and re-sorting them! You only need to place a dividing knife across both stacks so that the left half has the same total number of papers as the right half, and every score on the left is lower than or equal to every score on the right. By doing binary search on just the smaller stack, you find the right cut in seconds!
Reference: LeetCode #4 • Median of Two Sorted Arrays
Median Cut Visualizer
Optimal: Binary Search on PartitionInitialize Binary Search on Shorter Array
SEARCHINGWe ensure nums1 is the shorter array (m = 3 <= n = 4). We search for the partition cut in nums1 within range [low = 0, high = 3]. Total elements = 7, so left half needs exactly (3 + 4 + 1) / 2 = 4 elements.
Initialize pointers on shorter array: let low = 0, high = m;Why the Optimal Solution? (Deriving the Approach)
From full array merges to logarithmic partition cuts without extra memory.
Full Array Merge
Combine both arrays into a single sorted array of size (m + n) and index directly into the middle.
Two-Pointer Counting
Simulate merging using two pointers up to (m + n) / 2 without creating a new array. Still takes O(m + n) time.
What is a Median?
A median splits a dataset into equal Left and Right halves where every element on Left is ≤ every element on Right.
Dependent Cuts
If we pick partitionX elements from nums1, we MUST pick partitionY = (m + n + 1)/2 - partitionX from nums2!
Binary Search Cut
Binary search the cut in the shorter array! Check if maxLeft ≤ minRight. Each comparison cuts search space in half.
Complexity Analysis for Binary Search Cut
Binary search cuts the partition search space of the shorter array in half with every iteration. Since m <= n, at most log₂(m) steps are needed.
Only a constant number of integer pointers and boundary variables are maintained; no auxiliary array is allocated.
Two-Pointer Counting Approach
O(m + n) Time
Simulate the merge process using two pointers p1 and p2. Track the previous and current values until reaching step (m + n) / 2.
for (let count = 0; count <= Math.floor(total / 2); count++) {
prev = curr;
if (p1 < m && (p2 >= n || nums1[p1] <= nums2[p2])) {
curr = nums1[p1++];
} else {
curr = nums2[p2++];
}
} While it saves memory by avoiding a full merged array, it still checks elements sequentially. For large arrays with up to 1,000,000 items, inspecting (m + n) / 2 elements fails the strict logarithmic requirement.
Optimal Approach: Binary Search on Partition
O(log(min(m, n))) Time ✓
Binary search the partition cut in the shorter array nums1. The cut in nums2 is automatically derived: partitionY = (m + n + 1) / 2 - partitionX. Check if boundary conditions hold in O(1).
if (maxLeftX <= minRightY && maxLeftY <= minRightX) {
if ((m + n) % 2 === 1) return Math.max(maxLeftX, maxLeftY);
return (Math.max(maxLeftX, maxLeftY) + Math.min(minRightX, minRightY)) / 2;
} else if (maxLeftX > minRightY) {
high = partitionX - 1;
} else {
low = partitionX + 1;
}
Each check cuts the binary search range in half. By always operating on the smaller array (m ≤ n), at most log₂(m) comparisons are ever performed, requiring only O(1) auxiliary variables.
Example Test Cases
Official LeetCode ExamplesRules & Limits
Constraints- Array lengths up to 1,000
nums1.length == m,nums2.length == n,0 ≤ m, n ≤ 1000, and1 ≤ m + n ≤ 2000. - Wide value ranges
-10⁶ ≤ nums1[i], nums2[i] ≤ 10⁶. Use appropriate integer infinity sentinels. - Always sorted
Both input arrays are guaranteed to be sorted in non-decreasing order.
- Floating-point output
Return the answer as a 64-bit floating-point number (double).
Key Takeaways & Interview Mental Models
Binary Search on Answer Space
If nums1.length > nums2.length, immediately return findMedian(nums2, nums1). This guarantees partitionY ≥ 0 and optimizes the binary search runtime to O(log(min(m, n))).
When the cut falls at index 0 or index m, use -Infinity and +Infinity. This elegantly handles boundary edges without writing dozens of messy if statements.
This problem teaches an essential senior interview pattern: binary search does not have to search for a specific item in an array; it can search for an optimal partition boundary that balances two conditions.