sagelearnai

Median of Two Sorted Arrays

Difficulty: Hard · Pattern: Binary Search · LeetCode #4

Given two sorted arrays nums1 (length m) and nums2 (length n), return the median of all m + n values combined. Aim for O(log(min(m, n))).

Examples

text
nums1 = [1, 4], nums2 = [2, 3, 9]  →  3        (merged: 1 2 3 4 9)
nums1 = [1, 2], nums2 = [3, 4]     →  2.5
nums1 = [],     nums2 = [5]        →  5

Hints

  1. Merging costs O(m + n). For log time, think about cutting both arrays.
  2. Choose a cut i in nums1 and j = half − i in nums2 so the left side has half the elements.
  3. The cut is correct when every left element ≤ every right element: A[i−1] ≤ B[j] and B[j−1] ≤ A[i].

Approach

Let A be the shorter array. Binary search the number of elements i taken from A for the left half; then j = (m + n + 1) // 2 − i come from B. With sentinels ±∞ for out-of-range positions:

  • if A[i−1] > B[j], we took too many from A, so move left;
  • if B[j−1] > A[i], we took too few, so move right;
  • otherwise the partition is valid: the median is max(left side) (odd total) or the average of max(left) and min(right) (even total).

Complexity

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

Python solution
def findMedianSortedArrays(nums1, nums2):
    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
    INF = float('inf')
    while lo <= hi:
        i = (lo + hi) // 2
        j = half - i
        a_left = A[i - 1] if i > 0 else -INF
        a_right = A[i] if i < m else INF
        b_left = B[j - 1] if j > 0 else -INF
        b_right = B[j] if j < n else INF
        if a_left > b_right:
            hi = i - 1
        elif b_left > a_right:
            lo = i + 1
        else:
            if (m + n) % 2:
                return max(a_left, b_left)
            return (max(a_left, b_left) + min(a_right, b_right)) / 2
    return 0.0
JavaScript solution
function findMedianSortedArrays(nums1, nums2) {
  let A = nums1, B = nums2;
  if (A.length > B.length) [A, B] = [B, A];
  const m = A.length, n = B.length, half = (m + n + 1) >> 1;
  let lo = 0, hi = m;
  while (lo <= hi) {
    const i = (lo + hi) >> 1, j = half - i;
    const aL = i > 0 ? A[i - 1] : -Infinity, aR = i < m ? A[i] : Infinity;
    const bL = j > 0 ? B[j - 1] : -Infinity, bR = j < n ? B[j] : Infinity;
    if (aL > bR) hi = i - 1;
    else if (bL > aR) lo = i + 1;
    else return (m + n) % 2 ? Math.max(aL, bL) : (Math.max(aL, bL) + Math.min(aR, bR)) / 2;
  }
  return 0;
}