Try it first — give it 40 minutes
0/4 revealedStuck? Take one hint at a time. The struggle is where the pattern sticks.
The problem in plain English
You get two arrays, nums1 (length m) and nums2 (length n). Each one is sorted in non-decreasing order. Imagine pouring them together into one sorted list. Return the median of that list:
- if the total count is odd, the middle element;
- if it's even, the average of the two middle elements, as a decimal.
One array can be empty, but not both. The catch: the expected time is O(log(m + n)), so you can't merge.
Example: nums1 = [1, 3], nums2 = [2]. Together that's [1, 2, 3], so the median is 2.0. With nums1 = [1, 2], nums2 = [3, 4], together [1, 2, 3, 4], the median is (2 + 3) / 2 = 2.5.
Start with brute force
Merge the two arrays with two pointers, the way you did in Merge Two Sorted Lists. Then read off the middle. That's O(m + n) time. You can even stop halfway and use O(1) space.
It's correct, and in most interviews it's the right thing to say first. But the problem asks for a logarithmic answer. With m + n = 2,000 elements, a merge does about 1,000 steps and binary search does about 11. The interviewer wants to see the second one.
Building the intuition
This Hard is really two Medium ideas stacked together: "what does the median mean?" and "binary search on the answer".
Idea 1: the median is a cut, not a number you have to find. Take nums1 = [1, 3, 7, 9] and nums2 = [2, 4]. Merged, they'd be [1, 2, 3, 4, 7, 9], and the median sits between the 3rd and 4th elements. Now forget the merge. Draw a vertical line through each original array, so three elements end up on the left in total:
nums1: 1 3 | 7 9
nums2: 2 | 4Now the left side {1, 3, 2} has three elements and the right side {7, 9, 4} has three. Every left number is no bigger than every right number. That's exactly the median split. The median is (max of left + min of right) / 2 = (3 + 4) / 2 = 3.5. Check: merged [1, 2, 3, 4, 7, 9] gives (3 + 4) / 2. Correct.
So the job is: find two cuts, one in each array, that make a valid split.
Idea 2: one number decides everything. The left half must hold half = (m + n + 1) / 2 elements. (The + 1 gives the left side the extra element when the total is odd, so the median is then just the max of the left.) If you take i elements from nums1, you must take j = half − i from nums2. Pick i, and the whole cut is fixed.
Idea 3: how do you check a cut? Each array is already sorted, so inside one array the left part is automatically no bigger than the right part. You only need to check the two "cross" pairs:
nums1[i − 1] <= nums2[j](the last left element of the first array vs the first right element of the second);nums2[j − 1] <= nums1[i].
That's four numbers. If both hold, you've found the median.
Idea 4: which way to move? If nums1[i − 1] > nums2[j], the first array gave too many big numbers to the left. Make i smaller. If nums2[j − 1] > nums1[i], the first array gave too few. Make i bigger. One test tells you which half of the range to throw away. That's binary search.
The optimal approach
- If
nums1is longer, swap sonums1is the shorter one. Call the lengthsm ≤ n. - Set
half = (m + n + 1) / 2. Binary searchiover[0, m]. - For each
i, setj = half − i. Read the four neighboursleft1 = nums1[i − 1],right1 = nums1[i],left2 = nums2[j − 1],right2 = nums2[j]. A missing neighbour (the cut is at an edge) counts as −∞ on the left or +∞ on the right. - If
left1 <= right2andleft2 <= right1, you're done:- odd total: return
max(left1, left2); - even total: return
(max(left1, left2) + min(right1, right2)) / 2.
- odd total: return
- If
left1 > right2, sethi = i − 1. Otherwise setlo = i + 1.
The subtle detail: why search the shorter array? Two reasons. Speed: the range is [0, m], so you get O(log(min(m, n))). Safety: with m ≤ n, j = half − i always lands in [0, n]. If you searched the longer array, j could go negative and you'd index out of bounds.
The code
Every solution below is tested against the examples and edge cases before it ships. Pick your language — we'll remember it.
class Solution:
def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float:
# Binary search the shorter array, so the search is O(log(min(m, n)))
# and the cut in the longer array always lands inside it.
if len(nums1) > len(nums2):
nums1, nums2 = nums2, nums1
m, n = len(nums1), len(nums2)
half = (m + n + 1) // 2 # size of the left half (gets the extra element when the total is odd)
lo, hi = 0, m # i = how many elements of nums1 go to the left half
while lo <= hi:
i = (lo + hi) // 2
j = half - i # the rest of the left half comes from nums2
# Neighbours of the two cuts. An empty side acts as -inf / +inf.
left1 = nums1[i - 1] if i > 0 else float("-inf")
right1 = nums1[i] if i < m else float("inf")
left2 = nums2[j - 1] if j > 0 else float("-inf")
right2 = nums2[j] if j < n else float("inf")
if left1 <= right2 and left2 <= right1:
# Every left element <= every right element: this is the median cut.
if (m + n) % 2 == 1:
return float(max(left1, left2))
return (max(left1, left2) + min(right1, right2)) / 2
if left1 > right2:
hi = i - 1 # took too many from nums1
else:
lo = i + 1 # took too few from nums1
return 0.0 # inputs are sorted, so a valid cut always existsclass Solution {
public:
double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
// Binary search the shorter array: O(log(min(m, n))), and j never goes out of range.
if (nums1.size() > nums2.size()) return findMedianSortedArrays(nums2, nums1);
int m = nums1.size(), n = nums2.size();
int half = (m + n + 1) / 2; // left half gets the extra element when the total is odd
int lo = 0, hi = m; // i = how many elements of nums1 go to the left half
while (lo <= hi) {
int i = lo + (hi - lo) / 2;
int j = half - i; // the rest of the left half comes from nums2
// Neighbours of the two cuts. An empty side acts as -inf / +inf.
long long left1 = i > 0 ? nums1[i - 1] : LLONG_MIN;
long long right1 = i < m ? nums1[i] : LLONG_MAX;
long long left2 = j > 0 ? nums2[j - 1] : LLONG_MIN;
long long right2 = j < n ? nums2[j] : LLONG_MAX;
if (left1 <= right2 && left2 <= right1) {
// Every left element <= every right element: this is the median cut.
if ((m + n) % 2 == 1) return (double)max(left1, left2);
return (max(left1, left2) + min(right1, right2)) / 2.0;
}
if (left1 > right2) hi = i - 1; // took too many from nums1
else lo = i + 1; // took too few from nums1
}
return 0.0; // inputs are sorted, so a valid cut always exists
}
};class Solution {
public double findMedianSortedArrays(int[] nums1, int[] nums2) {
// Binary search the shorter array: O(log(min(m, n))), and j never goes out of range.
if (nums1.length > nums2.length) return findMedianSortedArrays(nums2, nums1);
int m = nums1.length, n = nums2.length;
int half = (m + n + 1) / 2; // left half gets the extra element when the total is odd
int lo = 0, hi = m; // i = how many elements of nums1 go to the left half
while (lo <= hi) {
int i = lo + (hi - lo) / 2;
int j = half - i; // the rest of the left half comes from nums2
// Neighbours of the two cuts. An empty side acts as -inf / +inf.
long left1 = i > 0 ? nums1[i - 1] : Long.MIN_VALUE;
long right1 = i < m ? nums1[i] : Long.MAX_VALUE;
long left2 = j > 0 ? nums2[j - 1] : Long.MIN_VALUE;
long right2 = j < n ? nums2[j] : Long.MAX_VALUE;
if (left1 <= right2 && left2 <= right1) {
// Every left element <= every right element: this is the median cut.
if ((m + n) % 2 == 1) return (double) Math.max(left1, left2);
return (Math.max(left1, left2) + Math.min(right1, right2)) / 2.0;
}
if (left1 > right2) hi = i - 1; // took too many from nums1
else lo = i + 1; // took too few from nums1
}
return 0.0; // inputs are sorted, so a valid cut always exists
}
}/**
* @param {number[]} nums1
* @param {number[]} nums2
* @return {number}
*/
var findMedianSortedArrays = function (nums1, nums2) {
// Binary search the shorter array: O(log(min(m, n))), and j never goes out of range.
if (nums1.length > nums2.length) [nums1, nums2] = [nums2, nums1];
const m = nums1.length, n = nums2.length;
const half = Math.floor((m + n + 1) / 2); // left half gets the extra element when the total is odd
let lo = 0, hi = m; // i = how many elements of nums1 go to the left half
while (lo <= hi) {
const i = Math.floor((lo + hi) / 2);
const j = half - i; // the rest of the left half comes from nums2
// Neighbours of the two cuts. An empty side acts as -Infinity / +Infinity.
const left1 = i > 0 ? nums1[i - 1] : -Infinity;
const right1 = i < m ? nums1[i] : Infinity;
const left2 = j > 0 ? nums2[j - 1] : -Infinity;
const right2 = j < n ? nums2[j] : Infinity;
if (left1 <= right2 && left2 <= right1) {
// Every left element <= every right element: this is the median cut.
if ((m + n) % 2 === 1) return Math.max(left1, left2);
return (Math.max(left1, left2) + Math.min(right1, right2)) / 2;
}
if (left1 > right2) hi = i - 1; // took too many from nums1
else lo = i + 1; // took too few from nums1
}
return 0; // inputs are sorted, so a valid cut always exists
};Dry run
nums1 = [1, 3, 8, 9, 15] (m = 5), nums2 = [7, 11, 18, 19, 21, 25] (n = 6). Total 11, so half = 6. The median is the 6th smallest.
| lo | hi | i | j | left1 | right1 | left2 | right2 | Check | Action |
|---|---|---|---|---|---|---|---|---|---|
| 0 | 5 | 2 | 4 | 3 | 8 | 19 | 21 | 19 > 8: too few from nums1 | lo = 3 |
| 3 | 5 | 4 | 2 | 9 | 15 | 11 | 18 | 9 <= 18 and 11 <= 15 ✓ | odd total → max(9, 11) = 11 |
Merged, the list is [1, 3, 7, 8, 9, 11, 15, 18, 19, 21, 25]. Its 6th element is 11. Two steps, no merge.
Complexity
- Time: O(log(min(m, n))). Binary search over the
m + 1possible values ofi, with O(1) work per step. - Space: O(1). A handful of variables. Nothing gets copied.
Edge cases and traps
- One array is empty.
m = 0, so the only option isi = 0. Bothnums1neighbours become ±∞ and the answer comes entirely fromnums2. The code handles it with no special case. - The cut sits at an edge.
i = 0means nothing fromnums1is on the left, soleft1 = −∞.i = mmeansright1 = +∞. Forget this and you'll indexnums1[-1], which Python silently reads as the last element. That's a nasty bug. - Integer division for the average.
(3 + 4) / 2must be3.5. In Java and C++, divide by2.0. - Overflow when using sentinels. In C++ and Java we use 64-bit
longfor the neighbours, so ±∞ can beLLONG_MIN/LLONG_MAX. Thenmax + minnever mixes an infinity with a real value in a way that overflowsint. A real pair likeINT_MAX + INT_MAXalso stays safe. - Duplicates across arrays. Use
<=, not<, in the check. With[1, 1]and[1, 1], every cut has equal neighbours, and<would reject all of them.
Say it in the interview
"The simple way is to merge with two pointers in O(m + n). To get logarithmic time, I think of the median as a cut. I split both arrays so the left side has half the elements and every left value is at most every right value. If I take i elements from the shorter array, the other array must give half minus i. So I binary search i. At each step I compare the four neighbours of the cuts. If the first array's left neighbour is too big, I move left. Otherwise I move right. That's O(log(min(m, n))) time and O(1) space."
Follow-ups interviewers ask
- "Find the k-th smallest of two sorted arrays instead." Same idea, with the left half sized
kinstead ofhalf. Or use the classic elimination: compare thek/2-th elements of each array and throw awayk/2elements from the side whose value is smaller. That's O(log k). - "What if the numbers arrive one at a time and you need the median after each?" That's a different problem: Find Median from Data Stream, in this same stage. It uses two heaps.
- "Why not merge? It's only O(m + n)." For one query, merging is fine. The partition idea matters when the arrays are huge or stored somewhere else, and you can only afford a few lookups.
Practise the same idea
This is a bonus day of the free DSA plan 🐸
90 problems in the order that builds on itself, one a day, with a walkthrough like this for each. Tick them off and keep your streak.
Get the full roadmap — free