4. Median of Two Sorted Arrays
Hard NeetCode 150 ↗ Open on LeetCode Source: NeetCode 150
Quick review
- Pattern
- Binary Search
- Time
- —
- Space
- —
Standard Solution (C++)
SummaryGiven two independently sorted integer arrays, find the median of the combined sequence without merging them. Return a double representing the middle value (or average of the two middle values) of the hypothetical merged sorted array.
Approach
- Binary search on the shorter array to find a partition point such that the left halves of both arrays together contain exactly
(m+n)/2elements. - At the correct partition, the largest element on any left side is no greater than the smallest element on any right side — this is the median invariant.
- Handle the odd/even total-length cases: for odd, the median is the max of the two left-side boundary values; for even, it is the average of that max and the min of the two right-side boundary values.
- Using
INT_MIN/INT_MAXas sentinels for empty left/right edges keeps the comparison logic uniform and branch-free.
#include <vector>
#include <algorithm>
#include <climits>
using namespace std;
class Solution {
public:
double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
// Always binary-search the shorter array to keep the loop O(log(min(m,n))).
if (nums1.size() > nums2.size())
return findMedianSortedArrays(nums2, nums1);
int m = (int)nums1.size();
int n = (int)nums2.size();
int half = (m + n + 1) / 2; // left half size of the merged array
int lo = 0, hi = m;
while (lo <= hi) {
// i = number of elements taken from nums1's left partition
int i = lo + (hi - lo) / 2;
// j = remaining elements needed for the left half
int j = half - i;
// Boundary values; sentinels handle edge partitions gracefully.
int maxLeft1 = (i == 0) ? INT_MIN : nums1[i - 1];
int minRight1 = (i == m) ? INT_MAX : nums1[i];
int maxLeft2 = (j == 0) ? INT_MIN : nums2[j - 1];
int minRight2 = (j == n) ? INT_MAX : nums2[j];
if (maxLeft1 <= minRight2 && maxLeft2 <= minRight1) {
// Correct partition found.
int leftMax = max(maxLeft1, maxLeft2);
int rightMin = min(minRight1, minRight2);
if ((m + n) % 2 == 1)
return leftMax; // odd total: median is the left-half max
return (leftMax + rightMin) / 2.0; // even total: average of middle two
} else if (maxLeft1 > minRight2) {
hi = i - 1; // nums1's left side is too large; move partition left
} else {
lo = i + 1; // nums2's left side is too large; move partition right
}
}
return 0.0; // unreachable for valid input
}
};
Time O(log(min(m, n))) Space O(1)
A canonical reference solution. Problem statement © LeetCode — see the official link above.
My Solution (C++)
#include <vector>
#include <algorithm>
using namespace std;
class Solution {
public:
int MAX = 1e7;
int findKthMin(vector<int>& nums1, int start1, vector<int>& nums2, int start2, int k) {
if (nums1.size() - start1 == 0)
return nums2[start2 + k - 1];
if (nums2.size() - start2 == 0)
return nums1[start1 + k - 1];
if (k == 1)
return std::min(nums1[start1], nums2[start2]);
int idx1 = start1 + k / 2 - 1;
int idx2 = start2 + k / 2 - 1;
int val1 = (idx1 < nums1.size()) ? nums1[idx1] : MAX;
int val2 = (idx2 < nums2.size()) ? nums2[idx2] : MAX;
if (val1 < val2)
return findKthMin(nums1, idx1 + 1, nums2, start2, k - k / 2);
return findKthMin(nums1, start1, nums2, idx2 + 1, k - k / 2);
}
double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
// use binary tree to solve the problem
int m = nums1.size();
int n = nums2.size();
int k = (m + n + 1) / 2;
int med = findKthMin(nums1, 0, nums2, 0, k); // k is 1-index
bool isOdd = (m + n) % 2;
if (isOdd)
return med;
else
return (med + findKthMin(nums1, 0, nums2, 0, k + 1)) / 2.0;
}
};
// Time: O(log(m+n))
// Space: O(log(m+n)) My own solution and notes, as I wrote them.
▶ Run it — editable in-browser playground with a sample driver C++
Your solution plus an auto-generated main() and sample input so Run produces output. The driver and inputs are unverified — edit freely; Reset restores this starting point.
C++ ▶ Runnable Auto-generated driver with sample input — unverified.
Runs in a free public sandbox (Wandbox). Output and timing include network latency; don't paste secrets.