Video in progress
How do you find the median of two sorted arrays combined, without merging them, in O(log(min(n, m)))?
I binary-search for a cut point in the shorter array: the two left parts together must hold half of the elements, and the maximum of the left parts must not exceed the minimum of the right parts. Once that point is found, the median comes from the four numbers at the boundary.
📖 Answer
The simple solution is to merge and take the middle, O(n + m). That is often enough, but the interviewer asks for the logarithmic version.
The idea: we cut a at position i and b at position j, with i + j = (n + m + 1) / 2. For the cut to be valid we need a[i-1] <= b[j] and b[j-1] <= a[i]. We pick i by binary search, and j follows from it.
static double median(int[] a, int[] b) {
if (a.length > b.length) return median(b, a); // a is the shorter one
int n = a.length, m = b.length, half = (n + m + 1) / 2;
int lo = 0, hi = n;
while (lo <= hi) {
int i = (lo + hi) >>> 1, j = half - i;
int aLeft = i == 0 ? Integer.MIN_VALUE : a[i - 1];
int aRight = i == n ? Integer.MAX_VALUE : a[i];
int bLeft = j == 0 ? Integer.MIN_VALUE : b[j - 1];
int bRight = j == m ? Integer.MAX_VALUE : b[j];
if (aLeft <= bRight && bLeft <= aRight) {
int leftMax = Math.max(aLeft, bLeft);
if ((n + m) % 2 == 1) return leftMax;
return ((long) leftMax + Math.min(aRight, bRight)) / 2.0;
}
if (aLeft > bRight) hi = i - 1; else lo = i + 1;
}
throw new IllegalArgumentException("massivlar saralanmagan");
}
Why do we search in the shorter one? That way j = half - i is never negative or greater than m, and no index goes out of bounds. Forgetting this is the most common mistake.
Integer.MIN_VALUE and MAX_VALUE are sentinels meaning "there is no element on this side". Even if the array contains those values themselves, the logic holds, because the comparison uses <=. For even total length, the cast to long keeps the sum of two large ints from overflowing.
This is another form of "binary search on the answer": we search not by value but by cut position. The same idea finds the k-th element of two sorted arrays, for instance when combining sorted results from two shards without fully merging them.
Sign up to mark studied questions and save your progress.