Median of Two Sorted Arrays solution explained
The O(log(min(m, n))) answer to Median of Two Sorted Arrays binary searches how many items to take from the shorter list for the left half of the combined order; the rest of the left half comes from the other list. A split is correct when the largest value on the left of each list is no bigger than the smallest value on the right of the other, and the median is then read from the four values around the split.
By Evin JohnPublished 9 min read
What is being asked
You get two lists of integers, each sorted from smallest to largest, with lengths m and n. At least one is non-empty. Return the median of the combined values: the middle value if the total count is odd, or the average of the two middle values if it is even. The common requirement is a running time logarithmic in the input sizes, which rules out building the combined list.
| First list | Second list | Median | Combined order |
|---|---|---|---|
| [2, 9, 14] | [5, 11] | 9.0 | 2, 5, 9, 11, 14 |
| [2, 9, 14] | [5, 11, 20] | 10.0 | 2, 5, 9, 11, 14, 20 |
| [] | [3, 8] | 5.5 | 3, 8 |
| [1, 2, 3] | [10, 11, 12, 13] | 10.0 | Every value of the first list comes first |
| [30] | [1, 2, 3, 4, 5] | 3.5 | The single value lands at the end |
Confirm the return type (a float when the total is even), whether both lists can be empty (usually not), and whether values can repeat (they can, and the method below handles it).
Why it is considered hard
The linear answer is easy, so the difficulty is all in the logarithmic one: you binary search for a position rather than a value, across two lists at once, with four boundary values that can each be missing. Interviewers use it to see whether you can define the right invariant, handle empty sides without a pile of special cases, and keep calm through a longer derivation. Expect a follow-up asking for the k-th smallest value instead of the median.
Linear answer: merge
Walk both lists with two indexes, always taking the smaller head, as in the merge step of merge sort. Then read the middle of the merged list. That is O(m + n) time and space. You can avoid the extra list by counting up to the middle position and remembering the last two values seen, which saves memory but keeps O(m + n) time.
def median_by_merge(a, b):
merged, i, j = [], 0, 0
while i < len(a) and j < len(b):
if a[i] <= b[j]:
merged.append(a[i])
i += 1
else:
merged.append(b[j])
j += 1
merged.extend(a[i:])
merged.extend(b[j:])
n = len(merged)
if n % 2:
return float(merged[n // 2])
return (merged[n // 2 - 1] + merged[n // 2]) / 2Logarithmic answer: search the split
Imagine the combined sorted order cut into a left half and a right half, with the left half holding one extra item when the total is odd. Call its size half = (m + n + 1) // 2. Some number of those left items come from list a, say cut_a, and the rest, cut_b = half - cut_a, come from list b. Choosing cut_a fixes everything. The choice is right when every value on the left is at most every value on the right. Since each list is sorted on its own, that reduces to two checks across the lists: a's last left value is at most b's first right value, and b's last left value is at most a's first right value.
If a's last left value is too big, you took too many from a, so search smaller cut_a. Otherwise b's last left value is too big, you took too few from a, so search larger. That is a monotone yes or no, so binary search over cut_a from 0 to m works. Search over the shorter list: then cut_b can never go negative or past the end of the longer one, and the search costs O(log(min(m, n))).
def median_sorted_pair(a, b):
if not a and not b:
raise ValueError("both lists are empty")
if len(a) > len(b):
a, b = b, a # binary search over the shorter list
m, n = len(a), len(b)
half = (m + n + 1) // 2 # size of the left side of the split
low, high = 0, m
while low <= high:
cut_a = (low + high) // 2 # items taken from a for the left side
cut_b = half - cut_a # the rest come from b
a_left = a[cut_a - 1] if cut_a > 0 else float("-inf")
a_right = a[cut_a] if cut_a < m else float("inf")
b_left = b[cut_b - 1] if cut_b > 0 else float("-inf")
b_right = b[cut_b] if cut_b < n else float("inf")
if a_left <= b_right and b_left <= a_right:
if (m + n) % 2:
return float(max(a_left, b_left))
return (max(a_left, b_left) + min(a_right, b_right)) / 2
if a_left > b_right:
high = cut_a - 1 # took too many from a
else:
low = cut_a + 1 # took too few from a
raise ValueError("inputs must be sorted")#include <algorithm>
#include <climits>
#include <stdexcept>
#include <vector>
double medianSortedPair(const std::vector<int>& x, const std::vector<int>& y) {
if (x.empty() && y.empty()) throw std::invalid_argument("both lists are empty");
const std::vector<int>& a = x.size() <= y.size() ? x : y; // shorter
const std::vector<int>& b = x.size() <= y.size() ? y : x;
const int m = a.size();
const int n = b.size();
const int half = (m + n + 1) / 2;
int low = 0;
int high = m;
while (low <= high) {
const int cutA = low + (high - low) / 2;
const int cutB = half - cutA;
const long long aLeft = cutA > 0 ? a[cutA - 1] : LLONG_MIN;
const long long aRight = cutA < m ? a[cutA] : LLONG_MAX;
const long long bLeft = cutB > 0 ? b[cutB - 1] : LLONG_MIN;
const long long bRight = cutB < n ? b[cutB] : LLONG_MAX;
if (aLeft <= bRight && bLeft <= aRight) {
const long long leftMax = std::max(aLeft, bLeft);
if ((m + n) % 2 == 1) return static_cast<double>(leftMax);
const long long rightMin = std::min(aRight, bRight);
return (leftMax + rightMin) / 2.0;
}
if (aLeft > bRight) {
high = cutA - 1;
} else {
low = cutA + 1;
}
}
throw std::invalid_argument("inputs must be sorted");
}When the split is valid and the total is even, both leftMax and rightMin are real values, never sentinels, because each half holds at least one item. Adding them as 64-bit integers avoids the overflow you would get summing two large 32-bit ints, and dividing by 2.0 gives the fractional median.
A trace
| low..high | cut_a, cut_b | a_left, a_right | b_left, b_right | Verdict |
|---|---|---|---|---|
| 0..3 | 1, 2 | 2, 9 | 11, 20 | b_left 11 > a_right 9: take more from a, low = 2 |
| 2..3 | 2, 1 | 9, 14 | 5, 11 | 9 <= 11 and 5 <= 14: valid |
The total is even, so the median is the average of max(9, 5) and min(14, 11), which is (9 + 11) / 2 = 10.0. The left half is 2, 5, 9 and the right half is 11, 14, 20, as the merged order confirms.
Complexity
| Approach | Time | Extra space |
|---|---|---|
| Merge everything | O(m + n) | O(m + n) |
| Merge to the middle only, two variables | O(m + n) | O(1) |
| k-th smallest by discarding k/2 at a time | O(log(m + n)) | O(1) iterative |
| Binary search on the shorter split | O(log(min(m, n))) | O(1) |
Edge cases
- One list empty: the shorter list has length 0, so cut_a is 0 and the median comes from the other list alone.
- Every value of one list smaller than every value of the other, like [1, 2, 3] and [10, 11, 12, 13].
- Lists of length 1 and 1, the smallest even total.
- Repeated values across both lists, such as [4, 4] and [4, 4].
- Values near the integer limits in fixed-width languages, where the sum of the two middle values no longer fits in 32 bits.
- Very different lengths, like one value against a long list.
Where people get stuck
- Searching over the longer list, which lets cut_b go negative or past the end.
- Using half = (m + n) // 2 for odd totals and then reading the median from the wrong side.
- Special-casing each empty side by hand instead of using infinity sentinels, which multiplies branches and bugs.
- Adding the two middle values as 32-bit ints in C++ or Java, which overflows when both are large.
- Returning integer division for an even total, giving 10 where 10.5 was correct.
How to explain it out loud
Fictional example
- Candidate
- Merging works in m plus n. To do better, I'll think of the merged order cut into a left half and a right half. If I decide how many left-half items come from the shorter list, the count from the other list is fixed.
- Candidate
- The cut is right when the largest left value in each list is at most the smallest right value in the other. If the shorter list's left side is too big, I took too many from it; otherwise too few. That's a binary search over the cut.
- Interviewer
- What about empty sides?
- Candidate
- I treat a missing left neighbor as minus infinity and a missing right neighbor as plus infinity, so the same comparison works at the ends. Once the cut is valid, the median is the max of the left values, or the average with the min of the right values when the total is even.
Related walkthroughs
If the boundary search feels unfamiliar, start with Binary Search and its first-position loop. Time Based Key-Value Store searches for a boundary inside one sorted history. The merge step used in the linear answer is the same two-index weave that Reorder List applies to linked list nodes. All problems are listed on the coding problems hub.
Working through it with Natively
This problem takes most people several attempts, so it pays to review each one. Natively transcribes your practice session on Mac or Windows, which makes it easy to find the point where your explanation of the split lost its thread. While you study, it can also read the problem from a screenshot and suggest how to set up the partition, which you can compare with your own derivation afterward. The AI assistant for coding interviews page describes the features.
Questions people ask
How do you find the median of two sorted arrays in log time?
Binary search how many items of the shorter list belong to the left half of the combined order. The split is valid when each list's largest left value is at most the other list's smallest right value; the median comes from those four values.
What is the time complexity of Median of Two Sorted Arrays?
O(log(min(m, n))) for the partition search, with O(1) extra space. Merging the lists is O(m + n).
Why search over the shorter array?
So the number of items taken from the longer array is always between zero and its length, which keeps every index valid and the search as short as possible.
Is merging an acceptable answer?
It is a correct and good first answer at O(m + n). Most interviewers then ask for the logarithmic method.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
