SDE & MLE Prep

4. Median of Two Sorted Arrays

Problem

Return the median of the union of two sorted arrays nums1 and nums2 (the mean of the two middle values when the total count is even). Aim for O(log(m + n)).

Example: [1,3] and [2] → 2.0; [1,2] and [3,4] → 2.5

Binary search a cut in the shorter array A at i, with cut j = half − i in B. The cut is correct when A[i-1] ≤ B[j] and B[j-1] ≤ A[i]; then the median comes from the four border values.

A:  1  3 | 8  9          left part: {1,3,2,4,5}   right: {8,9,7,10,...}
B:  2  4  5 | 7  10      maxLeft = 5, minRight = 7

Complexity: O(log min(m, n)).

class Solution:
    def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float:
        A, B = (nums1, nums2) if len(nums1) <= len(nums2) else (nums2, nums1)
        m, n = len(A), len(B)
        half = (m + n + 1) // 2
        lo, hi = 0, m
        while True:
            i = (lo + hi) // 2
            j = half - i
            al = A[i - 1] if i else float("-inf")
            ar = A[i] if i < m else float("inf")
            bl = B[j - 1] if j else float("-inf")
            br = B[j] if j < n else float("inf")
            if al <= br and bl <= ar:
                if (m + n) % 2:
                    return float(max(al, bl))
                return (max(al, bl) + min(ar, br)) / 2
            if al > br:
                hi = i - 1
            else:
                lo = i + 1