Median of Two Sorted Arrays

Pattern: Median of two sorted arrays

hard

Split both arrays so the left parts together hold half the values. Binary search the split point in the shorter array, checking that the last value on each left side is no bigger than the first value on the other right side.

The problem

Given two sorted arrays nums1 and nums2, return the median of all their values together, in O(log(m + n)) time. The median is the middle value, or the average of the two middle values when the total is even. For example, [1, 3] and [2] give 2, and [1, 2] and [3, 4] give 2.5.

The function name findMedianSortedArrays matches LeetCode. Use the link above for the exact statement and limits. The GFG link covers the same problem. So that all three languages print the same text, this guide's tests print the median with 4 decimals.

Think first

  • If you knew how many of the smaller half come from nums1, how many come from nums2?
  • How can you tell whether that choice is right without merging?
  • When it is right, where is the median?

Hints

    Brute force, and why it fails

    Merge the two arrays and take the middle: O(m + n) time. The rule asks for logarithmic time, and the split search takes O(log(min(m, n))).

    The key insight

    You do not need the merged order, only one correct cut. Choosing the cut in one array fixes it in the other, so there is just one number to binary search.

    Dry run

    nums1 = 1 20 
    nums2 = 3 41 
    lo0
    hi2
    half2

    nums1 = [1, 2] and nums2 = [3, 4]. The left part should hold (2 + 2 + 1) / 2 = 2 values. i is how many come from nums1, from 0 to 2.

    Step 1 of 4

    The plan

    make nums1 the shorter array
    half = (m + n + 1) / 2, lo = 0, hi = m
    while lo <= hi:
        i = (lo + hi) / 2, j = half - i
        aL = nums1[i - 1] or -inf, aR = nums1[i] or +inf
        bL = nums2[j - 1] or -inf, bR = nums2[j] or +inf
        if aL <= bR and bL <= aR:
            if m + n is odd: return max(aL, bL)
            return (max(aL, bL) + min(aR, bR)) / 2
        if aL > bR: hi = i - 1
        else: lo = i + 1
    

    Complexity

    Time
    O(log(min(m, n)))
    Space
    O(1)

    The search runs over the shorter array only.

    Edge cases

    • One array empty: the median of the other.
    • All values equal: that value.
    • Very different lengths, as in [10, 20] and six small values: the split puts both 10 and 20 on the right.
    I've built my logic, show the code

    Java

    class Solution {
        public double findMedianSortedArrays(int[] nums1, int[] nums2) {
            if (nums1.length > nums2.length) return findMedianSortedArrays(nums2, nums1);   // search the shorter one
            int m = nums1.length, n = nums2.length, half = (m + n + 1) / 2;
            int lo = 0, hi = m;                     // i = how many values the left half takes from nums1
            while (lo <= hi) {
                int i = (lo + hi) / 2, j = half - i;
                int aLeft = i > 0 ? nums1[i - 1] : Integer.MIN_VALUE, aRight = i < m ? nums1[i] : Integer.MAX_VALUE;
                int bLeft = j > 0 ? nums2[j - 1] : Integer.MIN_VALUE, bRight = j < n ? nums2[j] : Integer.MAX_VALUE;
                if (aLeft <= bRight && bLeft <= aRight) {                // every left value <= every right value
                    if ((m + n) % 2 == 1) return Math.max(aLeft, bLeft);
                    return (Math.max(aLeft, bLeft) + (double) Math.min(aRight, bRight)) / 2;
                }
                if (aLeft > bRight) hi = i - 1;     // took too many from nums1
                else lo = i + 1;                    // took too few
            }
            return 0;                               // not reached for sorted input
        }
    }

    C++

    class Solution {
    public:
        double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
            if (nums1.size() > nums2.size()) return findMedianSortedArrays(nums2, nums1);   // search the shorter one
            int m = static_cast<int>(nums1.size()), n = static_cast<int>(nums2.size()), half = (m + n + 1) / 2;
            int lo = 0, hi = m;                     // i = how many values the left half takes from nums1
            while (lo <= hi) {
                int i = (lo + hi) / 2, j = half - i;
                int aLeft = i > 0 ? nums1[i - 1] : INT_MIN, aRight = i < m ? nums1[i] : INT_MAX;
                int bLeft = j > 0 ? nums2[j - 1] : INT_MIN, bRight = j < n ? nums2[j] : INT_MAX;
                if (aLeft <= bRight && bLeft <= aRight) {                // every left value <= every right value
                    if ((m + n) % 2 == 1) return max(aLeft, bLeft);
                    return (max(aLeft, bLeft) + static_cast<double>(min(aRight, bRight))) / 2;
                }
                if (aLeft > bRight) hi = i - 1;     // took too many from nums1
                else lo = i + 1;                    // took too few
            }
            return 0;                               // not reached for sorted input
        }
    };

    Python

    class Solution:
        def findMedianSortedArrays(self, nums1: list[int], nums2: list[int]) -> float:
            if len(nums1) > len(nums2):
                nums1, nums2 = nums2, nums1         # search the shorter one
            m, n = len(nums1), len(nums2)
            half = (m + n + 1) // 2
            lo, hi = 0, m                           # i = how many values the left half takes from nums1
            while lo <= hi:
                i = (lo + hi) // 2
                j = half - i
                a_left = nums1[i - 1] if i > 0 else float("-inf")
                a_right = nums1[i] if i < m else float("inf")
                b_left = nums2[j - 1] if j > 0 else float("-inf")
                b_right = nums2[j] if j < n else float("inf")
                if a_left <= b_right and b_left <= a_right:   # every left value <= every right value
                    if (m + n) % 2 == 1:
                        return float(max(a_left, b_left))
                    return (max(a_left, b_left) + min(a_right, b_right)) / 2
                if a_left > b_right:
                    hi = i - 1                      # took too many from nums1
                else:
                    lo = i + 1                      # took too few
            return 0.0                              # not reached for sorted input

    Common mistakes

    • Searching the longer array, which lets j go negative.
    • Averaging in integer arithmetic, which turns 2.5 into 2.
    • Forgetting the infinity values at the ends.

    Similar problems