Median of two sorted arrays of same size

Find the median of two sorted arrays of equal length, taking values in order only up to the middle.

You are given two sorted arrays of integers, a and b, that both hold the same number of values, n, with n at least 1. Return the median of all 2n values together. The median is the middle value once the values are in sorted order. When the count is even, it is the average of the two middle values.

Example 1
Input: a = [1, 12, 15, 26, 38], b = [2, 13, 17, 30, 45]
Output: 16.0
Explanation: in sorted order, the values are [1, 2, 12, 13, 15, 17, 26, 30, 38, 45]; the middle two are 15 and 17.
Example 2
Input: a = [1, 2], b = [3, 4]
Output: 2.5
Solution

The Idea

Imagine five friends standing in a line, from shortest to tallest. The median height is the height of the third friend, the one in the middle. With six friends there is no single middle person, so the median is the average of the third and the fourth.

Here the line always has 2n values, an even count, so the median is always the average of two middle values. In Example 1, n is 5 and there are 10 values. Lined up, they read 1, 2, 12, 13, 15, 17, 26, 30, 38, 45. The fifth and sixth are 15 and 17, and their average is 16.

The plain way to get there is to copy both arrays into one new sorted array of 10 values and read the middle. But look at what the median used: only the first six values of that line. The four after 17 played no part. So do we need to build the whole line at all?

We only need the values in sorted order, one at a time, up to the middle. Both arrays are sorted, so the smallest value not yet taken is always at the front of a or at the front of b. Compare the two fronts, take the smaller one, and move that array's front one place along. Look at the picture below.

The arrays a = 1, 12, 15, 26, 38 and b = 2, 13, 17, 30, 45. Taken in sorted order: 1, 2, 12, 13, 15, 17 in steps 1 to 6. Step 5 takes 15 (prev) and step 6 takes 17 (curr), and (15 + 17) / 2 = 16. The last four values are never taken.

The bottom row, labelled "taken in sorted order", shows the values in the order they are taken, with the step number under each one and the array it comes from, a or b, above it. Step 1 compares the fronts 1 and 2 and takes 1 from a. Step 2 compares 12 with 2 and takes 2 from b. The array that wins the comparison keeps alternating until step 5 takes 15 from a and step 6 takes 17 from b. Those two, marked prev and curr, are the middle values, and (15 + 17) / 2 = 16. The grey values 26, 30, 38 and 45, marked "never taken", are left alone.

So the median needs only the first half of the sorted line, and only the last two values taken from it. Taking the smaller of two fronts, again and again, is the merge step of merge sort. Here it simply stops at the middle.

Solution Approach

Turning this half-way merge into code means settling three things: how many values to take, what to remember while taking them, and what to do when one array runs out.

How many values to take

Why not merge both arrays fully and read the middle? That works, but it fills a new array of 2n values just to read two of them. Counting positions from 0, the two middle values of 2n values sit at positions n - 1 and n. Both are known once n + 1 values have been taken, so the loop can stop there. In Example 1, n is 5, so it takes 6 values, as in the picture.

Remembering the last two values

What do we keep while taking values? Only the last two. curr holds the value taken most recently, and prev the one before it. Each step first copies curr into prev, then puts the new value in curr. After n + 1 steps, prev holds the value at position n - 1 and curr the value at position n.

When one array runs out

What if every value of one array is smaller than every value of the other? Take a = [5, 6] and b = [1, 2]. Steps 1 and 2 take 1 and 2 from b, and then b has no front left to compare. From then on, the value must come from a, so the check is: take from a when b is used up, or when the front of a is not bigger than the front of b.

Can both arrays run out? No. Before each step at most n values have been taken. So if all n values of one array are gone, nothing has been taken from the other yet, and it still has all its values.

Java Solution

The method findMedian works in these steps:

  1. First, store the length of a in n. Start two indices at the front of each array: i for a and j for b. Set prev and curr to 0.
  2. Take n + 1 values with a for loop whose counter, count, runs from 0 to n.
  3. In each pass, copy curr into prev. Then take a[i] if b is used up (j >= n) or if a still has values and a[i] <= b[j]; otherwise take b[j]. The taken value goes into curr, and its index moves one place along.
  4. After the loop, return the average of prev and curr. The sum is computed as a double, a Java number type that keeps fractions and holds far bigger values than int.

The main method runs both examples, a case where all of b comes first, a single value in each array, and two arrays full of the largest int value.

Java
public class MedianOfTwoSortedArraysOfSameSize {

    public static double findMedian(int[] a, int[] b) {
        int n = a.length;
        int i = 0;                                  // next unused position in a
        int j = 0;                                  // next unused position in b
        int prev = 0;
        int curr = 0;
        for (int count = 0; count <= n; count++) {  // take n + 1 values in sorted order
            prev = curr;
            if (j >= n || (i < n && a[i] <= b[j])) {
                curr = a[i++];                      // b is used up, or a has the smaller front
            } else {
                curr = b[j++];
            }
        }
        return (prev + (double) curr) / 2.0;        // double: keeps the .5, cannot overflow
    }

    public static void main(String[] args) {
        int[] a = {1, 12, 15, 26, 38};
        int[] b = {2, 13, 17, 30, 45};
        System.out.println(findMedian(a, b));
        System.out.println(findMedian(new int[] {1, 2}, new int[] {3, 4}));
        System.out.println(findMedian(new int[] {5, 6}, new int[] {1, 2}));
        System.out.println(findMedian(new int[] {1}, new int[] {2}));
        int max = Integer.MAX_VALUE;
        System.out.println(findMedian(new int[] {max, max}, new int[] {max, max}));
    }
}

Running it prints:

Output
16.0
2.5
3.5
1.5
2.147483647E9

16.0 and 2.5 match Examples 1 and 2. The third line, 3.5, comes from a = [5, 6] and b = [1, 2]. After 1 and 2 used up b, the third step took 5 from a, so the middle values were 2 and 5.

Look at the fourth line: 1.5 is the average of 1 and 2. If the method returned (prev + curr) / 2 instead, Java would divide one int by another, drop the fraction, and give 1.0 for the same input.

The last line, 2.147483647E9, is 2,147,483,647, the largest value an int can hold, so the median of four copies of it is that value itself. Added as two int values, the same prev and curr go past that limit and wrap around to negative numbers, which is called overflow. Run on its own, (prev + curr) / 2.0 with these two values gives -1.0. The cast to double on curr makes Java add in double instead.

The original implementation, MedianOfTwoSortedArraysOfSameSize.java, is on GitHub.

Complexity

The method takes n + 1 values one by one and keeps only a few variables while doing it.

  • Time: O(n), because the loop runs n + 1 times, one more than the length of each array, and each pass does one comparison and moves one index.
  • Space: O(1). No merged array is built: the method keeps only i, j, prev, curr and count.

Because both arrays are sorted, the median can also be found by binary search, which halves the range of candidates at every step. That takes O(log n) steps and also works for arrays of different sizes: see Median of Two Sorted Arrays.