Median of Two Sorted Arrays

Find the middle value of two sorted arrays taken together, without merging them.

Given two sorted arrays nums1 and nums2, of lengths m and n, return the median of all their values taken together. The median is the middle value once all the values are in order, or the average of the two middle values when there is an even number of them. The run time must be O(log(m + n)).

Example 1
Input: nums1 = [1, 3], nums2 = [2]
Output: 2.0
Explanation: together the values are [1, 2, 3], and the median is 2.
Example 2
Input: nums1 = [1, 2], nums2 = [3, 4]
Output: 2.5
Explanation: together [1, 2, 3, 4]; the median is (2 + 3) / 2.
Solution

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] and nums2 = [7, 9, 10, 11]. There are 7 values, so the median is the 4th smallest. Picture all 7 in order, cut into a left half of 4 values and a right half of 3. The median is the largest value of the left half.

Which values make up the left half? Both arrays are sorted, so it is always the first few values of nums1 plus the first few values of nums2. If i values come from nums1, then j = 4 - i come from nums2. So the whole cut depends on one number, i, which can only be 0, 1, 2 or 3. In each array, the cut falls after the values it gives to the left half: after i values in nums1 and after j values in nums2.

How do we know a choice of i is right? Every value left of the cut must be no larger than every value right of it. Inside each array that already holds, because the array is sorted. Across the arrays it needs a check, on the values next to the cut. Call them aLeft and aRight, the last value of nums1 before its cut and the first value after it. In the same way, bLeft and bRight sit on either side of the cut in nums2. The cut is right when aLeft <= bRight and bLeft <= aRight. When a cut has nothing on its left, the missing value counts as minus infinity, written -∞. When it has nothing on its right, the missing value counts as plus infinity, +∞. Either way, its check always passes.

Look at the picture below. Each row tries one i, and the orange line is the cut in each array.

nums1 = [1, 3, 8] and nums2 = [7, 9, 10, 11] cut three ways. With i = 1 and j = 3, bLeft 10 is bigger than aRight 3, so take more from nums1. With i = 2 and j = 2, bLeft 9 is bigger than aRight 8, so take more from nums1. With i = 3 and j = 1, 8 is at most 9 and 7 is at most +∞: the correct cut, and the median is 8.

In the row i = 1, the left half holds 1 from nums1 and 7, 9, 10 from nums2. But bLeft is 10 and aRight is 3: a 10 sits on the left while a 3 sits on the right. The left half needs more values from nums1. The row i = 2 fails the same way, with 9 against 8.

In the last row, i = 3 takes all of nums1 and only 7 from nums2. Now 8 <= 9, and 7 <= +∞ because nothing is left in nums1 after its cut. The cut is right, and the median is the larger of 8 and 7, which is 8. Merged, the values are 1, 3, 7, 8, 9, 10, 11, and 8 is indeed the middle one.

The key point is that a failed check also tells us which way to go: too few values from nums1, or too many. So we never need to try every i. Try the middle of the choices still open, and each answer rules out half of them, like guessing a number when you are told "higher" or "lower". It is a binary search, not over the values, but over how many values nums1 gives to the left half.

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 merge sort, and stopping at the middle gives the right answer. But it steps over about half of all the values, so it takes O(m + n) time. The search for i looks at only a handful of values per try.

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 gives both, because Java's integer division drops the remainder: 7 values give 4, and 4 values give 2.

Searching over the shorter array

Does it matter which array i counts in? It does. j = leftSize - i must stay between 0 and the length of the other array. When i counts in the shorter array, that always holds, because leftSize is at least the shorter length and at most the longer one.

The other way round, j can go negative. With [1, 2, 3, 4, 5, 6, 7] and [8], leftSize is 4, and a search over the first array soon tries i = 5, so j = -1. Reading the value before that cut means index -2, and a version without the swap stops with an ArrayIndexOutOfBoundsException. So the method first swaps the arrays when the first one is longer.

Cuts at the edge of an array

What stands in for minus and plus infinity in Java? Integer.MIN_VALUE, the smallest int, plays -∞, and Integer.MAX_VALUE, the largest, plays +∞. No value in the arrays is smaller than the first or larger than the second, so a check against them always passes. This also covers an empty array, where i can only be 0.

Reading the median

Once the cut is right, the largest value on the left is max(aLeft, bLeft), and the smallest on the right is min(aRight, bRight). With an odd total the median is the first of these. With an even total it is the average of both, which may have a .5, so it is computed as a double.

The two values must be added as double too, not as int. Two values of 2,147,483,647, the largest int, add up to a number an int cannot hold, and the sum wraps around to -2. Halved, that gives -1.0 instead of 2,147,483,647.

Java Solution

The method findMedianSortedArrays takes the two arrays as a and b, and works in these steps:

  1. First, if a is longer than b, call the method again with the two swapped, so that a is the shorter array.
  2. Store the lengths in m and n, and the size of the left half in leftSize.
  3. Set lo = 0 and hi = m, the smallest and largest possible i. A while loop runs as long as lo <= hi. Each pass takes i halfway between them, and j = leftSize - i.
  4. Read aLeft, aRight, bLeft and bRight, the four values next to the cut. Where a cut is at the edge of its array, use Integer.MIN_VALUE or Integer.MAX_VALUE instead.
  5. If aLeft <= bRight and bLeft <= aRight, the cut is right: return Math.max(aLeft, bLeft) for an odd total, or the average of that and Math.min(aRight, bRight), in double, for an even total.
  6. Otherwise, if aLeft > bRight, too many values came from a, so set hi = i - 1. If not, too few came from a, so set lo = i + 1.
  7. 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 method runs both examples, the arrays from the picture, an empty array with [7], a longer first array, and two copies of the largest int.

Java
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:

Output
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] and [7, 9, 10, 11], and the search takes the same three tries as the rows in the picture: i = 1, then 2, then 3.

The 7.0 comes from an empty a. There i can only be 0, so aLeft is Integer.MIN_VALUE and aRight is Integer.MAX_VALUE. Both checks pass at once, and the median is bLeft, the 7. The 4.5 comes from [1, 2, 3, 4, 5, 6, 7] and [8], the pair that throws without the swap. With the swap, i counts in [8], and the median is the average of 4 and 5.

Look at the last line: 2.147483647E9 is how Java prints the double 2,147,483,647, where E9 means times 109. It is the right median of two copies of the largest int, because the sum was taken in double.

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))). i 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)).
  • 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.