Median of Two Sorted Arrays — Binary Search on Partition

Sanjeev SharmaSanjeev Sharma
2 min read

Advertisement

Problem 337 · Median of Two Sorted Arrays

Difficulty: Hard · Pattern: Binary Search on Partition

Find the median in O(log(min(m,n))).

Intuition

Binary search on the smaller array. For a partition at i in A and j=(m+n+1)//2 - i in B, check if left max <= right min. Adjust accordingly.

Solutions

# Python
def findMedianSortedArrays(nums1, nums2):
    A, B = nums1, nums2
    if len(A) > len(B): A, B = B, A
    m, n = len(A), len(B)
    lo, hi = 0, m
    while lo <= hi:
        i = (lo+hi)//2
        j = (m+n+1)//2 - i
        A_left = A[i-1] if i > 0 else float('-inf')
        A_right = A[i] if i < m else float('inf')
        B_left = B[j-1] if j > 0 else float('-inf')
        B_right = B[j] if j < n else float('inf')
        if A_left <= B_right and B_left <= A_right:
            if (m+n) % 2 == 1: return max(A_left, B_left)
            return (max(A_left,B_left) + min(A_right,B_right)) / 2
        elif A_left > B_right: hi = i-1
        else: lo = i+1
// Java
public double findMedianSortedArrays(int[] A, int[] B) {
    if (A.length>B.length) return findMedianSortedArrays(B,A);
    int m=A.length, n=B.length, lo=0, hi=m;
    while (lo<=hi) {
        int i=(lo+hi)/2, j=(m+n+1)/2-i;
        int aL=i>0?A[i-1]:Integer.MIN_VALUE, aR=i<m?A[i]:Integer.MAX_VALUE;
        int bL=j>0?B[j-1]:Integer.MIN_VALUE, bR=j<n?B[j]:Integer.MAX_VALUE;
        if (aL<=bR&&bL<=aR) {
            if ((m+n)%2==1) return Math.max(aL,bL);
            return (Math.max(aL,bL)+Math.min(aR,bR))/2.0;
        } else if (aL>bR) hi=i-1; else lo=i+1;
    }
    return 0;
}

Complexity

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

Advertisement

Sanjeev Sharma

Written by

Sanjeev Sharma

Full Stack Engineer · E-mopro