Median of Two Sorted Arrays

Binary search on the partition of the smaller array — find a split with equal-sized halves and left ≤ right on both sides.

Hard
Time O(log min(m, n)) Space O(1)
LeetCode
6 min read
binary-search divide-and-conquer

Problem#

Find the median of two sorted arrays in O(log(m+n)).

Examples#

  • [1,3], [2]2.0.
  • [1,2], [3,4]2.5.

Constraints#

  • 0 <= m + n <= 2000, total ≥ 1.

Approach#

Binary-search the partition point in the shorter array. For each candidate i (split of A), compute j = half - i (split of B). Check A[i-1] <= B[j] and B[j-1] <= A[i]. Median is then derived from the four boundary values.

Solution#

Median of Two Sorted Arrays
class Solution {
public:
double findMedianSortedArrays(vector<int>& A, vector<int>& B) {
if (A.size() > B.size()) return findMedianSortedArrays(B, A);
int m = A.size(), n = B.size();
int total = m + n, half = (total + 1) / 2;
int lo = 0, hi = m;
while (lo <= hi) {
int i = (lo + hi) / 2;
int j = half - i;
int Aleft = (i == 0) ? INT_MIN : A[i - 1];
int Aright = (i == m) ? INT_MAX : A[i];
int Bleft = (j == 0) ? INT_MIN : B[j - 1];
int Bright = (j == n) ? INT_MAX : B[j];
if (Aleft <= Bright && Bleft <= Aright) {
if (total % 2) return max(Aleft, Bleft);
return (max(Aleft, Bleft) + min(Aright, Bright)) / 2.0;
} else if (Aleft > Bright) hi = i - 1;
else lo = i + 1;
}
return 0.0;
}
};

Editorial#

Searching on the smaller array bounds the work to O(log min(m, n)). The four boundary checks with INT_MIN/INT_MAX sentinels handle empty-half edges cleanly. Half-size is (total + 1) / 2 so the odd-length case picks the median on the left side.

Complexity#

  • Time: O(log min(m, n)).
  • Space: O(1).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.