Skip to content
TheChatArchiveThe Chat Archive
Grok 4.1 Fast· xaiHugging Face Frontier Reasoning Traces

Design an algorithm to find the median of two sorted arrays in O(log n) time.

  1. User

    Design an algorithm to find the median of two sorted arrays in O(log n) time.

  2. Assistant

    Algorithm to Find Median of Two Sorted Arrays in O(log min(m, n)) Time

    Problem Overview

    • Given two sorted arrays A (length m) and B (length n), find the median of the combined sorted array.
    • Median definition:
      • If m + n is odd: The middle element.
      • If m + n is even: Average of the two middle elements.
    • Goal: Achieve O(log min(m, n)) time complexity using binary search (no merging required).

    Key Insight: Binary Search on Partitions

    • We don't merge the arrays. Instead, we partition them into left and right halves such that:
      • The left half contains exactly (m + n + 1) // 2 elements (handles both odd/even cases elegantly).
      • All elements in left ≤ all elements in right, i.e., max(left) ≤ min(right).
    • Binary search on the partition point i in the smaller array (assume m ≤ n; swap if needed).
      • i = # elements from A in left half (ranges 0 to m).
      • j = (m + n + 1) // 2 - i (# elements from B in left half).
    • For a candidate (i, j):
      • Check: A[i-1] ≤ B[j] and B[j-1] ≤ A[i].
      • Use ±∞ for boundary cases (e.g., i=0 means no A[i-1]).
    • Adjust search:
      • If A[i-1] > B[j]: Too many large elements from A → decrease i.
      • If B[j-1] > A[i]: Too few from A → increase i.

    Why O(log min(m, n))?

    • Binary search over m (smaller array): O(log m) iterations.
    • Each iteration: O(1) time (constant-time checks).

    Pseudocode

    def findMedianSortedArrays(A, B):
        # Ensure A is the smaller array
        if len(A) > len(B):
            A, B = B, A
        
        m, n = len(A), len(B)
        low, high = 0, m
        
        while low <= high:
            i = (low + high) // 2          # Partition in A
            j = (m + n + 1) // 2 - i       # Partition in B
            
            # Handle boundaries with infinities
            leftA = float('-inf') if i == 0 else A[i-1]
            rightA = float('inf') if i == m else A[i]
            leftB = float('-inf') if j == 0 else B[j-1]
            rightB = float('inf') if j == n else B[j]
            
            # Valid partition?
            if leftA <= rightB and leftB <= rightA:
                # Compute median
                if (m + n) % 2 == 1:  # Odd total
                    return max(leftA, leftB)
                else:                 # Even total
                    return (max(leftA, leftB) + min(rightA, rightB)) / 2.0
            elif leftA > rightB:
                high = i - 1           # Move left in A
            else:                      # leftB > rightA
                low = i + 1
        
        # Should not reach here if inputs are valid sorted arrays
        raise ValueError("Input arrays must be sorted")
    

    Example Walkthrough

    Input: A = [1, 3], B = [2] (m=2, n=1 → swap to A=[2], B=[1,3]; total=3, odd)

    • low=0, high=1
    • i=0, j=2-0=2 → leftA=-∞, rightA=2, leftB=3, rightB=∞ → -∞≤∞ (true), 3≤2 (false) → low=1
    • i=1, j=2-1=1 → leftA=2, rightA=∞, leftB=1, rightB=3 → 2≤3 (true), 1≤∞ (true) → valid
    • Odd: max(2,1) = 2 ✓ (combined: [1,2,3] median=2)

    Input: A = [1, 3], B = [2, 4] (m=2,n=2, even)

    • i=1, j=2 → leftA=1,rightA=3,leftB=2,rightB=4 → 1≤4,2≤3 ✓
    • Even: (max(1,2) + min(3,4))/2 = (2+3)/2 = 2.5 ✓ (combined: [1,2,3,4])

    Edge Cases Handled

    • One empty array: e.g., A=[], B=[1,2,3] → median=2.
    • All elements equal: Works (any valid partition).
    • m=1, n=1: Correctly handles.
    • Large inputs: Efficient (no full scan).

    Proof Sketch (Correctness)

    • Invariant: Binary search converges to valid (i,j) because partition conditions are monotonic.
    • (m+n+1)//2 ensures left has the "upper median" position.

    This is the optimal linearithmic solution (better than merge-based O(m+n)). Implement in any language with minor index adjustments!

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.