Logarithmic Median of Two Sorted Arrays

Medium · Coding & Algorithms · Software Engineer · Technical Screen

Problem Statement

Given two integer sequences nums1 (of length m) and nums2 (of length n), each already arranged in ascending (non-decreasing) order, implement find_median_sorted_arrays(nums1, nums2) to return the median of all m + n numbers as a float.

One of the two sequences may be empty, provided that m + n >= 1. Suppose combined denotes all m + n elements placed in non-decreasing order (0-indexed):

  • When m + n is odd, the median is the single central value float(combined[(m + n) // 2]).
  • When m + n is even, the median is the arithmetic mean of the two central values: (combined[(m + n) // 2 - 1] + combined[(m + n) // 2]) / 2.0.

Your algorithm must run in O(log(m + n)) time and use O(1) auxiliary memory—you may not materialize a combined list or walk linearly across the inputs.

Examples

Example 1

  • Input: nums1 = [2, 8], nums2 = [4, 6, 10]
  • Output: 6.0
  • Explanation: The combined sorted order is [2, 4, 6, 8, 10] (5 values total), whose middle entry at index 2 is 6.0.

Example 2

  • Input: nums1 = [-4, 3], nums2 = [6, 11]
  • Output: 4.5
  • Explanation: Across the 4 sorted elements [-4, 3, 6, 11], the two inner values are 3 and 6, averaging to (3 + 6) / 2.0 = 4.5.

Example 3

  • Input: nums1 = [], nums2 = [9]
  • Output: 9.0
  • Explanation: nums1 contributes zero elements, leaving [9] with median 9.0.

Example 4

  • Input: nums1 = [-2, 4], nums2 = [4, 4]
  • Output: 4.0
  • Explanation: Repeated numbers are preserved ([-2, 4, 4, 4]); the two middle entries are both 4, yielding 4.0.

Constraints

  • 0 <= len(nums1), len(nums2) <= 10^5
  • len(nums1) + len(nums2) >= 1
  • -2^31 <= nums1[i], nums2[j] <= 2^31 - 1
  • nums1 and nums2 are each sorted in non-decreasing order.
  • Time complexity must be O(log(m + n)) and auxiliary space complexity must be O(1).

Step-by-step walkthrough

  1. Understand the goal: find the middle without merging

    We are given two sorted integer arrays nums1 (length m) and nums2 (length n), where m + n >= 1. Imagine merging them into one sorted array of length total_len = m + n:

    Odd total (m + n = 5):   [ 2,  4, | 6 |, 8, 10 ]  -> middle index 2 -> median = 6.0
    Even total (m + n = 4):  [-4, | 3,   6 |, 11 ]    -> average of indices 1 & 2 -> (3 + 6) / 2 = 4.5
    

    Merging the two arrays with two pointers takes O(m + n) time (up to 200,000 steps). Our target is O(log(m + n)) time and O(1) extra space, which rules out building a merged array or even walking linearly to the middle. Instead, we need a way to jump straight to the median boundary using binary search.

  2. Reframe "median" as a balanced cut across both arrays

    Think about what the median actually separates: it splits all total_len numbers into a left half containing the smallest numbers and a right half containing the largest numbers.

    Let's set the exact size of the left half to:

    left_half_size = (total_len + 1) // 2
    

    Why add + 1 before integer division // 2? Check both cases:

    • When total_len = 5 (odd): left_half_size = (5 + 1) // 2 = 3. The left half holds 3 elements and the right half holds 2, so the single middle element sits at the very top of the left half (max(left_half)).
    • When total_len = 4 (even): left_half_size = (4 + 1) // 2 = 2. Both halves hold 2 elements, so the median is the average of max(left_half) and min(right_half).

    So if we can figure out which elements belong in the left half such that every number on the left is <= every number on the right, we immediately know the median!

  3. Link the two cuts and check only four border numbers

    Because both nums1 and nums2 are already sorted, the smallest elements contributed by nums1 must be a prefix nums1[0 : cut1] of length cut1, and the smallest elements contributed by nums2 must be a prefix nums2[0 : cut2] of length cut2.

    Crucially, cut1 and cut2 are locked together because the total number of elements on the left must equal left_half_size:

    cut2 = left_half_size - cut1
    

    Picking cut1 automatically determines cut2! Look at the four border elements sitting right next to the two cuts:

    nums1:  [ ...  left1  |  right1  ... ]     left1 = nums1[cut1 - 1],  right1 = nums1[cut1]
    nums2:  [ ...  left2  |  right2  ... ]     left2 = nums2[cut2 - 1],  right2 = nums2[cut2]
             <-- left --> | <-- right -->
    

    When is every left element <= every right element? - left1 <= right1 is already guaranteed because nums1 is sorted. - left2 <= right2 is already guaranteed because nums2 is sorted. - So we only need to check the two cross-array pairs: 1. left1 <= right2 2. left2 <= right1

    What if a cut sits at the very beginning (cut1 == 0, meaning we took zero elements from nums1) or the very end (cut1 == m, meaning we took all of nums1)? Then there is no element on that side of the cut, so we use float("-inf") for a missing left neighbor and float("inf") for a missing right neighbor. Minus infinity is always <= everything on the right, and plus infinity is always >= everything on the left!

  4. Why binary search works — and why we search the shorter array

    Suppose our trial cut1 fails one of the two cross-checks. Which way should cut1 move?

    • Case 1 (left1 > right2): The last element we took from nums1 (left1) is too big — it belongs in the right half! We took too many elements from nums1, so we must move cut1 left: hi = cut1 - 1.
    • Case 2 (left2 > right1): The last element we took from nums2 (left2) is bigger than right1! Taking more elements from nums1 pushes cut1 right and simultaneously pulls cut2 = left_half_size - cut1 left, shrinking left2. So we move cut1 right: lo = cut1 + 1.

    Notice why we swap first so nums1 is the shorter array (m <= n): we binary-search cut1 across [0, m], and we need cut2 = left_half_size - cut1 to always stay inside [0, n]. Let's verify both extremes when m <= n:

    • Smallest cut2 (at cut1 = m): (m + n + 1) // 2 - m = (n - m + 1) // 2 >= 0 because n >= m.
    • Largest cut2 (at cut1 = 0): (m + n + 1) // 2 <= (n + n + 1) // 2 = n because m <= n.

    So cut2 can never go negative or exceed n! Even better, binary-searching the shorter array takes O(log(min(m, n))) steps, which is always within O(log(m + n)).

  5. Write the binary search loop

    Putting those pieces together gives a short, clean while lo <= hi: loop:

    if len(nums1) > len(nums2):
        nums1, nums2 = nums2, nums1
    
    m = len(nums1)
    n = len(nums2)
    total_len = m + n
    left_half_size = (total_len + 1) // 2
    
    lo = 0
    hi = m
    while lo <= hi:
        cut1 = (lo + hi) // 2
        cut2 = left_half_size - cut1
    
        left1 = nums1[cut1 - 1] if cut1 > 0 else float("-inf")
        right1 = nums1[cut1] if cut1 < m else float("inf")
        left2 = nums2[cut2 - 1] if cut2 > 0 else float("-inf")
        right2 = nums2[cut2] if cut2 < n else float("inf")
    
        if left1 > right2:
            hi = cut1 - 1
        elif left2 > right1:
            lo = cut1 + 1
        else:
            left_max = max(left1, left2)
            if total_len % 2 == 1:
                return float(left_max)
            right_min = min(right1, right2)
            return (left_max + right_min) / 2.0
    
  6. Trace Examples 1, 2, and 3

    Example 1: nums1 = [2, 8] (m=2), nums2 = [4, 6, 10] (n=3)
      m <= n already holds; total_len = 5 (odd), left_half_size = (5 + 1) // 2 = 3
      - Round 1: lo=0, hi=2 -> cut1=1, cut2=2
          nums1: [ 2 | 8 ]       -> left1 = 2, right1 = 8
          nums2: [ 4, 6 | 10 ]   -> left2 = 6, right2 = 10
          Check: 2 <= 10 and 6 <= 8 -> VALID!
          Odd total -> float(max(2, 6)) = 6.0
    
    Example 2: nums1 = [-4, 3] (m=2), nums2 = [6, 11] (n=2)
      total_len = 4 (even), left_half_size = (4 + 1) // 2 = 2
      - Round 1: lo=0, hi=2 -> cut1=1, cut2=1
          left1=-4, right1=3, left2=6, right2=11 -> left2 (6) > right1 (3) -> lo = 2
      - Round 2: lo=2, hi=2 -> cut1=2, cut2=0
          left1=3, right1=+inf, left2=-inf, right2=6 -> VALID!
          Even total -> (max(3, -inf) + min(+inf, 6)) / 2.0 = (3 + 6) / 2.0 = 4.5
    
    Example 3: nums1 = [] (m=0), nums2 = [9] (n=1)
      total_len = 1 (odd), left_half_size = 1
      - Round 1: lo=0, hi=0 -> cut1=0, cut2=1
          left1=-inf, right1=+inf, left2=9, right2=+inf -> VALID! -> 9.0
    
  7. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    
    
    def find_median_sorted_arrays(nums1: List[int], nums2: List[int]) -> float:
        # Always binary-search on the shorter array so cut2 = left_half_size - cut1
        # is guaranteed to stay within [0, len(nums2)] without out-of-bounds indices.
        if len(nums1) > len(nums2):
            nums1, nums2 = nums2, nums1
    
        m = len(nums1)
        n = len(nums2)
        total_len = m + n
        # Size of the combined left partition; +1 puts the single middle element on the left when odd.
        left_half_size = (total_len + 1) // 2
    
        # Search range [lo, hi] over cut1 = count of elements taken from nums1 (0 .. m inclusive).
        lo = 0
        hi = m
        while lo <= hi:
            cut1 = (lo + hi) // 2
            cut2 = left_half_size - cut1
    
            # Border values immediately left and right of each cut.
            # Use -inf / +inf sentinels when a cut sits at index 0 or n/m so boundary checks stay valid.
            left1 = nums1[cut1 - 1] if cut1 > 0 else float("-inf")
            right1 = nums1[cut1] if cut1 < m else float("inf")
            left2 = nums2[cut2 - 1] if cut2 > 0 else float("-inf")
            right2 = nums2[cut2] if cut2 < n else float("inf")
    
            if left1 > right2:
                # Left partition took an element from nums1 larger than nums2's right side; move cut1 left.
                hi = cut1 - 1
            elif left2 > right1:
                # Left partition took too few from nums1 (and too many from nums2); move cut1 right.
                lo = cut1 + 1
            else:
                # Valid partition found: every element on the left is <= every element on the right.
                left_max = max(left1, left2)
                if total_len % 2 == 1:
                    return float(left_max)
                right_min = min(right1, right2)
                return (left_max + right_min) / 2.0
    
        raise ValueError("Input arrays must be sorted in non-decreasing order.")
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Imagine two lines of students already sorted from shortest to tallest, and your job is to find the median height (the middle value when the total count is odd, or the average of the two middle values when even) without merging everyone into one giant line. Instead of moving students around, you just place one divider rope across Line 1 and a second divider rope across Line 2 so that the total number of students standing to the left of both ropes equals half the group ((m + n + 1) // 2). Once you pick where Rope 1 goes (cut1 students from nums1), Rope 2's spot (cut2 = left_half_size - cut1 students from nums2) is forced automatically! You only have to check whether the tallest student left of Rope 1 is <= the shortest student right of Rope 2, and vice versa — and because moving Rope 1 right makes its value grow while pushing Rope 2 left makes its value shrink, that monotonicity (values changing cleanly in one direction as the index increases) lets us find the exact rope position with binary search (repeatedly halving the range of candidate positions [lo, hi]).

Why does the obvious approach fall short? Concatenating and sorting takes O((m + n) log(m + n)) time and O(m + n) memory, and even a two-pointer walk up to the middle still reads (m + n) / 2 elements — up to 100,000 reads when m = n = 100,000. Binary-searching the partition (the pair of cuts splitting all elements into smaller and larger halves) on the shorter array finds the answer in at most ~17 loop iterations!

Let's trace Example 2 (nums1 = [-4, 3] and nums2 = [6, 11]), where total_len = 4 and left_half_size = (4 + 1) // 2 = 2, using sentinel values (-inf and +inf placeholder extremes used when a cut sits at the very start or end of an array):

1. lo = 0, hi = 2 -> try cut1 = 1, so cut2 = 2 - 1 = 1:
     nums1: [ -4 | 3 ]   -> left1 = -4,   right1 = 3
     nums2: [  6 | 11 ]  -> left2 = 6,    right2 = 11
     Cross-check: left2 (6) > right1 (3) -> took too few from nums1! Move lo = 2.

2. lo = 2, hi = 2 -> try cut1 = 2, so cut2 = 2 - 2 = 0:
     nums1: [ -4, 3 | ]  -> left1 = 3,    right1 = +inf
     nums2: [ | 6, 11 ]  -> left2 = -inf, right2 = 6
     Cross-check: 3 <= 6 and -inf <= +inf -> valid partition!
     Even total -> (max(3, -inf) + min(+inf, 6)) / 2.0 = (3 + 6) / 2.0 = 4.5

Complexity

Let m and n be the lengths of nums1 and nums2.

  • Time: O(log(min(m, n))), which satisfies and improves upon the O(log(m + n)) requirement. We swap references in O(1) so nums1 has length min(m, n), and the binary search starts with min(m, n) + 1 candidate cut positions (0 through min(m, n)), cutting the search range in half on every iteration while doing O(1) index reads and comparisons per step.
  • Space: O(1). Rebinding nums1, nums2 = nums2, nums1 only swaps two local variable references without copying either array, and the loop maintains just a handful of integer indices and four border values.

Edge cases

  • One array is empty ([] and [9], or [] and [4, 7]): After swapping, m = 0, so lo = hi = 0, cut1 = 0, cut2 = left_half_size, left1 = -inf, right1 = +inf, and the median is read directly from nums2 on the very first iteration.
  • Single total element ([] and [9]): total_len = 1 is odd, left_half_size = 1, and the odd branch returns float(max(left1, left2)) without touching right_min (+inf).
  • Disjoint value ranges ([-4, 3] and [6, 11]): The valid cut sits all the way at cut1 = m or cut1 = 0; the -inf and +inf sentinels keep all comparisons well-defined without special-case if branches.
  • Repeated values across the cut ([-2, 4] and [4, 4]): Multiple cut1 positions can satisfy left1 <= right2 and left2 <= right1, and every valid split yields left_max = 4 and right_min = 4, returning 4.0.
  • Negative numbers and 32-bit integer extremes (-2^31 and 2^31 - 1): Python integers have arbitrary precision, so left_max + right_min never overflows (in C++ or Java, cast to long or double before adding two 2147483647 values).
  • Wildly unbalanced sizes (m = 1, n = 100,000): Swapping so we search the 1-element array finishes in at most 2 iterations (cut1 = 0 or cut1 = 1).

Common mistakes

  • Binary-searching the longer array without clamping bounds: If len(nums1) > len(nums2), picking cut1 near 0 makes cut2 = left_half_size - cut1 > len(nums2), and picking cut1 near len(nums1) makes cut2 < 0 (which silently indexes from the end of nums2 in Python!). Swapping so len(nums1) <= len(nums2) prevents both bugs completely.
  • Forgetting edge sentinels when cut1 == 0 or cut2 == 0: Evaluating nums1[cut1 - 1] when cut1 == 0 reads nums1[-1] (the largest element of nums1!) instead of -inf in Python, causing baffling wrong answers.
  • Mismatching left_half_size with the odd-case return value: Using (m + n + 1) // 2 puts the extra middle element on the left (return float(left_max)), whereas (m + n) // 2 puts the extra element on the right (return float(right_min)). Mixing the two is off by one element on every odd-length input.
  • Using integer division // 2 instead of / 2.0 for even totals: Truncates 4.5 down to 4 on [-4, 3] and [6, 11].
  • Slicing arrays (nums1[:cut1]) inside the loop: In Python, slicing copies up to m elements and turns each step into O(m), silently ruining both O(log(min(m, n))) time and O(1) space.

Alternative approaches

  • Eliminate k // 2 elements per step (find_kth helper): Generalize to finding the k-th smallest element (1-based) by comparing nums1[k // 2 - 1] and nums2[k // 2 - 1] and discarding the smaller prefix of k // 2 elements in O(log(m + n)) time (called once for odd totals, twice for even totals).
  • Binary search on the numeric value: Binary-search an integer candidate x in [-2^31, 2^31 - 1] and count how many elements across both arrays are <= x using bisect_right. Takes O(log(value_range) * (log m + log n)) (~32 outer steps), which is slightly slower for two arrays in RAM but scales naturally to many arrays across machines.

Follow-up questions

  • How can you adapt the partition binary search to return the k-th smallest value (1 <= k <= m + n) across both arrays? Replace left_half_size with k so cut1 + cut2 == k, and clamp the search interval for cut1 to [max(0, k - n), min(k, m)] (since k might be tiny, like k = 1, or close to m + n, where an unconstrained cut2 = k - cut1 could otherwise fall outside [0, n]). Once left1 <= right2 and left2 <= right1 hold, the k-th smallest element is simply max(left1, left2), still in O(log(min(m, n))) time and O(1) space.
  • Suppose K sorted arrays live on K separate servers; how would you compute the global median while minimizing network traffic? Partitioning cuts across K arrays simultaneously becomes multidimensional, so switch to value-space binary search: a coordinator picks a candidate value mid between the global minimum and maximum, asks all K servers in parallel to count how many local elements are <= mid via local binary search (bisect_right), and sums the K counts to decide whether to search lower or higher. For 32-bit integers, ~32 coordinator rounds find any target rank while sending only single integers over the network instead of shipping millions of array elements.
  • If integers arrive continuously in an unsorted stream instead of two static sorted arrays, how would you maintain the running median? Maintain two heaps: a max-heap (a binary tree array that pops its largest value in O(log N) time, simulated in Python by negating numbers in heapq) holding the smaller half of numbers seen so far, and a min-heap (popping its smallest value in O(log N) time) holding the larger half, rebalanced so their sizes differ by at most 1. Every new number inserts and rebalances in O(log N) time, and reading the current median from the heap top(s) takes O(1) time.

Follow-up questions

Similar questions

More Rippling interview questions

All 106 Rippling questions →