DSA and coding Level 4 This level · 2 of 2
Hard dsa binary-search

Median of Two Sorted Arrays

The 30 second answer

I need the median of two already-sorted arrays in logarithmic time, so I cannot merge them. I binary-search a cut in the shorter array; the cut in the longer array is then fixed by the median position. When every value on the left of the cut is less than or equal to every value on the right, the median is made of the max of the left and, if the total length is even, the min of the right.

Could you say this in an interview?

Problem Given two sorted integer arrays, return the median of the two arrays as if they were merged, in O(log (m + n)) time. Original: LeetCode 4: Median of Two Sorted Arrays.

Understanding the prompt A merged copy would be linear and is not allowed under the official brief. The median is the middle value when m + n is odd, or the average of the two middle values when it is even. Either array may be empty, but not both. This problem is named in a public Microsoft interview report.

Pattern recognition Boundary binary search on the partition point of the shorter array, which is a divide-and-conquer view of the two sequences.

Brute force Merge into one sorted array and pick the middle: O(m + n) time and space. Two pointers to the middle without storing the merge still take linear time.

Optimal Force a to be the shorter array. Search a cut i in 0..a.length, and set j so that i + j is the size of the left half, (m + n + 1) / 2. Let aLeft, aRight, bLeft and bRight be the values just left and right of each cut, or minus/plus infinity at the ends. If aLeft <= bRight and bLeft <= aRight the partition is correct: the median is max(aLeft, bLeft) when the total is odd, otherwise the average of that max and min(aRight, bRight). If aLeft is too large, move the cut in a to the left; otherwise move it to the right.

Alternatives A recursive k-th element search that throws away half of one array at each step is equivalent and a little more general. Merging is the fallback if the interviewer drops the logarithmic requirement.

Java solution

public class MedianOfTwoSortedArrays {
    static double findMedianSortedArrays(int[] a, int[] b) {
        if (a.length > b.length) return findMedianSortedArrays(b, a);
        int m = a.length, n = b.length;
        int lo = 0, hi = m;
        int half = (m + n + 1) / 2;
        while (lo <= hi) {
            int i = lo + (hi - lo) / 2;
            int j = half - i;
            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) {
                if ((m + n) % 2 == 1) return Math.max(aLeft, bLeft);
                return (Math.max(aLeft, bLeft) + Math.min(aRight, bRight)) / 2.0;
            }
            if (aLeft > bRight) hi = i - 1;
            else lo = i + 1;
        }
        throw new IllegalArgumentException("inputs are not sorted");
    }

    public static void main(String[] args) {
        System.out.println(findMedianSortedArrays(new int[] {1, 3}, new int[] {2}));    // 2.0
        System.out.println(findMedianSortedArrays(new int[] {1, 2}, new int[] {3, 4})); // 2.5
        System.out.println(findMedianSortedArrays(new int[] {}, new int[] {1}));        // 1.0
        System.out.println(findMedianSortedArrays(new int[] {0, 0}, new int[] {0, 0})); // 0.0
    }
}

Complexity O(log (min(m, n))) time, because the search runs only on the shorter array. O(1) extra space.

Edge cases

  • Official samples: [1,3] and 2 return 2.0; [1,2] and [3,4] return 2.5.
  • One array is empty, as in [] and 1, which returns 1.0.
  • All values equal, as in [0,0] and [0,0], which returns 0.0.

Follow-ups

  • k-th element of two sorted arrays is the same partition, with a different left-half size.
  • Find Median from Data Stream is the online version, usually solved with two heaps.

Tests [1,3] and 2 return 2.0. [1,2] and [3,4] return 2.5. [] and 1 return 1.0. [0,0] and [0,0] return 0.0.

How to say it in the interview "I binary-search a cut in the shorter array so the left side of both arrays together has the right number of elements for the median. When the left values are all less than or equal to the right values, the median is the max of the left, averaged with the min of the right when the total length is even."

Sources (2)
  1. LeetCode 4: Median of Two Sorted Arraysleetcode.com
  2. LeetCode Discuss: Microsoft SDE-2 recent questions 2025 (candidate reports, secondary)leetcode.com
Previous
Next