Median of Two Sorted Arrays
Hard
Topics
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)).
The median of an array of length L is the (L/2)-th element if L is odd, or the average of the (L/2-1)-th and (L/2)-th elements if L is even (0-indexed, integer division). For this problem, return the integer part (floor) of the median.
Example 1
Input: nums1 = [1,3], nums2 = [2] Output: 2
Example 2
Input: nums1 = [1,2], nums2 = [3,4] Output: 2
Constraints
- 0 <= m, n <= 1000
- 1 <= m + n
- -10^6 <= nums1[i], nums2[i] <= 10^6
- Both arrays are sorted in non-decreasing order.
Editorial — intuition, approach, complexity and pitfalls
Intuition
Start with the obvious thing. Concatenate both arrays, sort, index the middle. That works and it is worth saying out loud, but re-sorting throws away the fact that both inputs are already sorted, and it costs O((m+n) log(m+n)).
So use the sortedness: walk the two arrays together like the merge step of merge sort and stop at the middle. Now it is O(m+n), and you do not even need to store the merged array — just count to the middle. For most problems that would be the answer.
It is not the answer here, because the problem asks for O(log(m+n)). Linear is too slow by the problem's own terms, and that constraint is the whole exercise.
The logarithmic idea comes from changing the question. Stop hunting for the median value and hunt for a cut instead. The median splits all m+n elements into a left half and a right half of known sizes. Because both arrays are sorted, such a split is fully described by one number: how many elements we take from the front of a. Take cut from a, and the count we need from b is forced — it is half - cut. So there is only one degree of freedom, and we can binary search it.
A cut is correct when nothing on either left side exceeds anything on the opposite right side:
a: . . . left_a | right_a . . .
b: . . . left_b | right_b . . .
valid iff left_a <= right_b AND left_b <= right_aIf left_a > right_b we took too much from a, so move the cut left. Otherwise we took too little, so move it right. Each step halves the range, and binary searching the shorter array makes it O(log(min(m,n))) — better than the O(log(m+n)) asked for.
Approach
- Swap so
ais the shorter array. The search range is then as small as possible, andhalf - cutcan never run off the end ofb. - Let
half = (m + n + 1) / 2, the size of the left part. The+1puts the extra element on the left when the total is odd, which makes the odd case read off the left side. - Binary search
cutover[0, m]. Deriveother = half - cut. - Read the four boundary values, substituting -infinity for a missing left neighbour and +infinity for a missing right one. Those sentinels are what let an empty array, or a cut at either end, fall out of the same comparison with no special cases.
- If the cut is valid: odd total returns
max(left_a, left_b); even total averages that withmin(right_a, right_b). - Otherwise move the cut toward the side that was too large and repeat.
Dry Run
Example 2, a = [1,2], b = [3,4]. Both have length 2, so no swap. total = 4, half = (4+1)/2 = 2, search range [0,2].
iteration 1: cut = 1, other = half - cut = 1
left_a = a[0] = 1 right_a = a[1] = 2
left_b = b[0] = 3 right_b = b[1] = 4
left_a <= right_b ? 1 <= 4 yes
left_b <= right_a ? 3 <= 2 NO -> b's left reaches too high
we took too little from a, so search right: lo = cut + 1 = 2
iteration 2: cut = 2, other = 0
left_a = a[1] = 2 right_a = none -> +inf
left_b = none -> -inf right_b = b[0] = 3
left_a <= right_b ? 2 <= 3 yes
left_b <= right_a ? -inf <= +inf yes -> valid cut
left half = [1,2] right half = [3,4]
total is even, so average the boundary pair:
(max(2, -inf) + min(+inf, 3)) / 2 = (2 + 3) / 2 = 2 (floored)Two iterations on a four-element input, and note that the first guess was wrong — the useful part of the trace is watching the invariant reject it.
Complexity
- Time — O(log(min(m,n))): one binary search over the shorter array's cut positions, with constant work per step. Strictly better than the O(log(m+n)) the problem asks for. For contrast, the concatenate-and-sort opener is O((m+n) log(m+n)) and the two-pointer merge is O(m+n).
- Space — O(1): four boundary values and two search bounds, no merged array. This is the other prize for not merging: the O(m+n) approach needs O(m+n) space unless you are careful to count rather than materialise.
Common Pitfalls
- Binary searching the longer array. It still terminates, but
other = half - cutcan then fall outsideb, and you inherit index checks that the swap removes for free. - Using
half = (m + n) / 2. With an odd total the extra element then sits on the right, andmax(left_a, left_b)is no longer the median. The+1is doing real work. - Comparing
left_awithleft_b, orright_awithright_b. The invariant is strictly cross-wise: each left against the opposite right. - Omitting the infinity sentinels and hand-writing the empty-array and cut-at-the-edge cases. That is where most attempts at this problem actually break — one of the two inputs being empty is a legal input here.
- Flooring a negative average by truncation. The answer wanted is the floor, and in Java and C++ integer division rounds toward zero, so
(-4 + -3) / 2gives -3 rather than the -4 required. UseMath.floorDiv, or correct the negative case by hand; Python's//already floors.
Full Solution — all languages
class Solution:
# Sentinels stand in for a missing neighbour at either edge, which is what
# lets an empty array and a cut at position 0 or m share the same branch.
NEG, POS = -10 ** 18, 10 ** 18
def findMedianSortedArrays(self, a, b):
if len(a) > len(b): # always binary search the shorter one
a, b = b, a
shorter, longer = len(a), len(b)
total = shorter + longer
if total == 0:
return 0
half = (total + 1) // 2 # +1 keeps the odd extra on the left
lo, hi = 0, shorter
while lo <= hi:
cut = lo + (hi - lo) // 2 # elements taken from a
other = half - cut # ... which forces the count from b
left_a = a[cut - 1] if cut > 0 else self.NEG
right_a = a[cut] if cut < shorter else self.POS
left_b = b[other - 1] if other > 0 else self.NEG
right_b = b[other] if other < longer else self.POS
if left_a <= right_b and left_b <= right_a:
if total % 2 == 1:
return max(left_a, left_b)
# // already floors toward negative infinity in Python
return (max(left_a, left_b) + min(right_a, right_b)) // 2
if left_a > right_b:
hi = cut - 1 # took too much from a
else:
lo = cut + 1 # took too little
return 0import java.util.*;
class Solution {
// Sentinels for a missing neighbour at either edge, so an empty array and a
// cut at position 0 or m need no special case.
private static final long NEG = Long.MIN_VALUE / 4;
private static final long POS = Long.MAX_VALUE / 4;
public int findMedianSortedArrays(int[] a, int[] b) {
if (a.length > b.length) { // always binary search the shorter one
int[] swap = a; a = b; b = swap;
}
int shorter = a.length, longer = b.length;
int total = shorter + longer;
if (total == 0) return 0;
int half = (total + 1) / 2; // +1 keeps the odd extra on the left
int lo = 0, hi = shorter;
while (lo <= hi) {
int cut = lo + (hi - lo) / 2; // elements taken from a
int other = half - cut; // ... which forces the count from b
long leftA = cut > 0 ? a[cut - 1] : NEG;
long rightA = cut < shorter ? a[cut] : POS;
long leftB = other > 0 ? b[other - 1] : NEG;
long rightB = other < longer ? b[other] : POS;
if (leftA <= rightB && leftB <= rightA) {
if (total % 2 == 1) return (int) Math.max(leftA, leftB);
long sum = Math.max(leftA, leftB) + Math.min(rightA, rightB);
// floorDiv, not /: integer division truncates toward zero, which
// would return -3 where the floor of -3.5 is -4.
return (int) Math.floorDiv(sum, 2);
}
if (leftA > rightB) hi = cut - 1; // took too much from a
else lo = cut + 1; // took too little
}
return 0;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
// Sentinels for a missing neighbour at either edge, so an empty array and a
// cut at position 0 or m need no special case.
static constexpr long long NEG = LLONG_MIN / 4;
static constexpr long long POS = LLONG_MAX / 4;
public:
int findMedianSortedArrays(vector<int>& a, vector<int>& b) {
if (a.size() > b.size()) return findMedianSortedArrays(b, a); // search the shorter
int shorter = a.size(), longer = b.size();
int total = shorter + longer;
if (total == 0) return 0;
int half = (total + 1) / 2; // +1 keeps the odd extra on the left
int lo = 0, hi = shorter;
while (lo <= hi) {
int cut = lo + (hi - lo) / 2; // elements taken from a
int other = half - cut; // ... which forces the count from b
long long leftA = cut > 0 ? a[cut - 1] : NEG;
long long rightA = cut < shorter ? a[cut] : POS;
long long leftB = other > 0 ? b[other - 1] : NEG;
long long rightB = other < longer ? b[other] : POS;
if (leftA <= rightB && leftB <= rightA) {
if (total % 2 == 1) return (int) max(leftA, leftB);
long long sum = max(leftA, leftB) + min(rightA, rightB);
// / truncates toward zero, so correct the negative case by hand
return (int) (sum >= 0 ? sum / 2 : (sum - 1) / 2);
}
if (leftA > rightB) hi = cut - 1; // took too much from a
else lo = cut + 1; // took too little
}
return 0;
}
};/**
* @param {number[]} a
* @param {number[]} b
* @return {number}
*/
var findMedianSortedArrays = function (a, b) {
if (a.length > b.length) [a, b] = [b, a]; // always search the shorter one
const shorter = a.length, longer = b.length;
const total = shorter + longer;
if (total === 0) return 0;
const half = Math.floor((total + 1) / 2); // +1 keeps the odd extra on the left
let lo = 0, hi = shorter;
while (lo <= hi) {
const cut = lo + Math.floor((hi - lo) / 2); // elements taken from a
const other = half - cut; // ... forces the count from b
// -Infinity / Infinity stand in for a missing neighbour at either edge
const leftA = cut > 0 ? a[cut - 1] : -Infinity;
const rightA = cut < shorter ? a[cut] : Infinity;
const leftB = other > 0 ? b[other - 1] : -Infinity;
const rightB = other < longer ? b[other] : Infinity;
if (leftA <= rightB && leftB <= rightA) {
if (total % 2 === 1) return Math.max(leftA, leftB);
// Math.floor, so a negative average rounds down as the problem wants
return Math.floor((Math.max(leftA, leftB) + Math.min(rightA, rightB)) / 2);
}
if (leftA > rightB) hi = cut - 1; // took too much from a
else lo = cut + 1; // took too little
}
return 0;
};