◀ THE GRIND — BINARY SEARCH

Median of Two Sorted Arrays

The drill: Two sorted arrays, one combined median — found faster than merging, in log time on the shorter array.

THE BRIEFING — THE FULL DRILL, IN MY OWN WORDS

Two arrays arrive, each already sorted in its own right but not merged together, and they can differ in length by any amount, including one of them being empty.

Treated as one combined sorted sequence, they have a well-defined median — the middle value if the combined count is odd, or the average of the two middle values if it's even.

The job is to report that median directly, without physically merging the two arrays into one — the faster solution has to reason about how the arrays interleave rather than construct that interleaving.

EX 01
nums1 = [1, 7] · nums2 = [4]
4
EX 02
nums1 = [2, 5] · nums2 = [3, 8]
4
EVEN TOTAL, AVERAGE OF THE MIDDLE TWO
EX 03
nums1 = [] · nums2 = [6]
6
ONE ARRAY EMPTY
THE HINTS — TAKE ONLY WHAT YOU NEED
HINT 1 THE NUDGE

A full merge is O(m+n) and already beats concatenate-and-sort. The log target means most elements must never be looked at.

HINT 2 THE STRUCTURE

A median is a partition: a left half and a right half of the combined data. Choose a cut in ONE array and the other array’s cut is forced.

HINT 3 ONE STEP FROM THE ANSWER

Binary-search the cut in the shorter array: if maxLeftA > minRightB move the cut left; if maxLeftB > minRightA move it right. ±∞ sentinels handle the edges.

COACH'S BOARD — THE PATTERN, STEP BY STEP
THE PARTITION LINEPATTERN · PARTITION SEARCHnums1 = [1, 3, 8] · nums2 = [7, 9, 10, 11]
1
3
8
7
9
10
11
STEP 1

Two sorted arrays: [1,3,8] and [7,9,10,11] — 7 values combined, median at index 3. Binary-search the partition of the shorter array.

STEP 1 / 6 · ← → WORK TOO
THE SPLITS — TWO PACES, TWO LANGUAGES
grind/median-of-two-sorted-arrays.pyRACE PACE
LANG ▸
PACE ▸
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 lo <= hi:
            i = (lo + hi) // 2
            j = half - 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:
                hi = i - 1
            elif b_left > a_right:
                lo = i + 1
            else:
                if (m + n) % 2 == 1:
                    return float(max(a_left, b_left))
                return (max(a_left, b_left) + min(a_right, b_right)) / 2.0
        return 0.0
TIME O(LOG MIN(M,N))SPACE O(1)PYTHON · RACE PACE · 22 LN

✓ CHIP-TIMED — ALL 4 SOLUTIONS RAN GREEN AGAINST SELF-AUTHORED CASES IN CI · JDK 21 · CPYTHON 3.12 · NOTHING PUBLISHES RED