Median of Two Sorted Arrays
Find the middle value of two sorted arrays taken together, without merging them.
Given two sorted arrays nums1nums2
Example 1
Output: 2.0
Explanation: together the values are [1, 2, 3], and the median is 2.
Example 2
Output: 2.5
Explanation: together [1, 2, 3, 4]; the median is (2 + 3) / 2.
The Idea
Line up the test scores of a class from lowest to highest, and the score in the middle is the median: half the class scored no more than it, and half no less. Now two classes have each lined up on their own, and you want the median of everyone. In Example 1, one line holds 1 and 3 and the other holds 2. Together they read 1, 2, 3, so the median is 2.
The obvious way is to merge the two lines into one and read off the middle. But the run time must be O(log(m + n)), far fewer steps than there are values. So we cannot even look at every value. How can we find the middle of the two lines without merging them?
Take a slightly bigger example: nums1 = [1, 3, 8]nums2 = [7, 9, 10, 11]
Which values make up the left half? Both arrays are sorted, so it is always the first few values of nums1nums2inums1j = 4 - inums2iinums1jnums2
How do we know a choice of iaLeftaRightnums1bLeftbRightnums2aLeft <= bRightbLeft <= aRight
Look at the picture below. Each row tries one i
In the row i = 1nums1nums2bLeftaRightnums1i = 2
In the last row, i = 3nums1nums2nums1
The key point is that a failed check also tells us which way to go: too few values from nums1inums1
Solution Approach
Turning that idea into code means settling five things: why merging is too slow, how many values go into the left half, which array to search, what to do at the edges of an array, and how to read the median once the cut is found.
Merging, and why it is too slow
Why not simply merge? Walking through both arrays together, as in the merge step of i
The size of the left half
How many values should the left half hold? With an even total, exactly half. With an odd total, the left half takes the extra value, so the median is its largest value. The formula leftSize = (m + n + 1) / 2
Searching over the shorter array
Does it matter which array ij = leftSize - iileftSize
The other way round, j[1, 2, 3, 4, 5, 6, 7][8]leftSizei = 5j = -1ArrayIndexOutOfBoundsException
Cuts at the edge of an array
What stands in for minus and plus infinity in Java? Integer.MIN_VALUEintInteger.MAX_VALUEi
Reading the median
Once the cut is right, the largest value on the left is max(aLeft, bLeft)min(aRight, bRight)double
The two values must be added as doubleintintint
Java Solution
The method findMedianSortedArraysab
- First, if
is longer thana , call the method again with the two swapped, so thatb is the shorter array.a - Store the lengths in
andm , and the size of the left half inn .leftSize - Set
andlo = 0 , the smallest and largest possiblehi = m . Ai loop runs as long aswhile . Each pass takeslo <= hi halfway between them, andi .j = leftSize - i - Read
,aLeft ,aRight andbLeft , the four values next to the cut. Where a cut is at the edge of its array, usebRight orInteger.MIN_VALUE instead.Integer.MAX_VALUE - If
andaLeft <= bRight , the cut is right: returnbLeft <= aRight for an odd total, or the average of that andMath.max(aLeft, bLeft) , inMath.min(aRight, bRight) , for an even total.double - Otherwise, if
, too many values came fromaLeft > bRight , so seta . If not, too few came fromhi = i - 1 , so seta .lo = i + 1 - For sorted input the loop always returns. If it ends without a right cut, the arrays were not sorted, and the method throws an
.IllegalArgumentException
The main[7]int
public class MedianOfTwoSortedArrays {
public static double findMedianSortedArrays(int[] a, int[] b) {
if (a.length > b.length) {
return findMedianSortedArrays(b, a); // search the shorter array
}
int m = a.length;
int n = b.length;
int leftSize = (m + n + 1) / 2; // size of the left half of the merged array
int lo = 0;
int hi = m;
while (lo <= hi) {
int i = lo + (hi - lo) / 2; // take i elements from a ...
int j = leftSize - i; // ... and the rest of the left half from b
int aLeft = (i == 0) ? Integer.MIN_VALUE : a[i - 1];
int aRight = (i == m) ? Integer.MAX_VALUE : a[i];
int bLeft = (j == 0) ? Integer.MIN_VALUE : b[j - 1];
int bRight = (j == n) ? Integer.MAX_VALUE : b[j];
if (aLeft <= bRight && bLeft <= aRight) {
// every value on the left is <= every value on the right: correct split
if ((m + n) % 2 == 1) {
return Math.max(aLeft, bLeft);
}
return (Math.max(aLeft, bLeft) + (double) Math.min(aRight, bRight)) / 2;
} else if (aLeft > bRight) {
hi = i - 1; // took too many from a
} else {
lo = i + 1; // took too few from a
}
}
throw new IllegalArgumentException("input arrays are not sorted");
}
public static void main(String[] args) {
System.out.println(findMedianSortedArrays(new int[] {1, 3}, new int[] {2}));
System.out.println(findMedianSortedArrays(new int[] {1, 2}, new int[] {3, 4}));
System.out.println(findMedianSortedArrays(new int[] {1, 3, 8}, new int[] {7, 9, 10, 11}));
System.out.println(findMedianSortedArrays(new int[] {}, new int[] {7}));
System.out.println(findMedianSortedArrays(new int[] {1, 2, 3, 4, 5, 6, 7}, new int[] {8}));
int max = Integer.MAX_VALUE;
System.out.println(findMedianSortedArrays(new int[] {max}, new int[] {max}));
}
}
Running it prints:
2.0
2.5
8.0
7.0
4.5
2.147483647E9
2.0 and 2.5 are the answers to Example 1 and Example 2. The 8.0 on the third line comes from [1, 3, 8][7, 9, 10, 11]i = 1
The 7.0 comes from an empty aiaLeftInteger.MIN_VALUEaRightInteger.MAX_VALUEbLeft[1, 2, 3, 4, 5, 6, 7][8]i[8]
Look at the last line: 2.147483647E9doubleE9intdouble
Complexity
The work is one binary search over how many values the shorter array gives to the left half.
- Time: O(log(min(m, n))).
has only one more choice than the shorter array has values, and each pass of the loop halves the choices left, with a fixed number of comparisons. That is within the required O(log(m + n)).i - Space: O(1). The method keeps only a few indexes and the four values next to the cut. The one call with swapped arrays adds a single stack frame.