Median of Two Sorted Arrays

Hard

Topics
ArrayBinary SearchDivide and Conquer

Given two sorted arrays nums1 and nums2 of size m and n respectively, return the median of the two sorted arrays. The overall run time complexity should be O(log(m+n)).

The median of an array of length L is the (L/2)-th element if L is odd, or the average of the (L/2-1)-th and (L/2)-th elements if L is even (0-indexed, integer division). For this problem, return the integer part (floor) of the median.

Example 1

a13
b2
merged123
Both inputs are already sorted, and the median wanted is of the two taken together. With an even total it is the average of the middle two — 2 here — so the answer need not be a value from either array, or even a whole number.
The two inputs and, below them, the merged order with the median shaded.
Input:  nums1 = [1,3], nums2 = [2]
Output: 2

Example 2

a12
b34
merged1234
Input:  nums1 = [1,2], nums2 = [3,4]
Output: 2

Constraints

  • 0 <= m, n <= 1000
  • 1 <= m + n
  • -10^6 <= nums1[i], nums2[i] <= 10^6
  • Both arrays are sorted in non-decreasing order.
Editorial — intuition, approach, complexity and pitfalls

Intuition

Start with the obvious thing. Concatenate both arrays, sort, index the middle. That works and it is worth saying out loud, but re-sorting throws away the fact that both inputs are already sorted, and it costs O((m+n) log(m+n)).

So use the sortedness: walk the two arrays together like the merge step of merge sort and stop at the middle. Now it is O(m+n), and you do not even need to store the merged array — just count to the middle. For most problems that would be the answer.

It is not the answer here, because the problem asks for O(log(m+n)). Linear is too slow by the problem's own terms, and that constraint is the whole exercise.

The logarithmic idea comes from changing the question. Stop hunting for the median value and hunt for a cut instead. The median splits all m+n elements into a left half and a right half of known sizes. Because both arrays are sorted, such a split is fully described by one number: how many elements we take from the front of a. Take cut from a, and the count we need from b is forced — it is half - cut. So there is only one degree of freedom, and we can binary search it.

A cut is correct when nothing on either left side exceeds anything on the opposite right side:

a:  . . . left_a | right_a . . .
b:  . . . left_b | right_b . . .

valid  iff  left_a <= right_b  AND  left_b <= right_a

If left_a > right_b we took too much from a, so move the cut left. Otherwise we took too little, so move it right. Each step halves the range, and binary searching the shorter array makes it O(log(min(m,n))) — better than the O(log(m+n)) asked for.

Approach

  1. Swap so a is the shorter array. The search range is then as small as possible, and half - cut can never run off the end of b.
  2. Let half = (m + n + 1) / 2, the size of the left part. The +1 puts the extra element on the left when the total is odd, which makes the odd case read off the left side.
  3. Binary search cut over [0, m]. Derive other = half - cut.
  4. Read the four boundary values, substituting -infinity for a missing left neighbour and +infinity for a missing right one. Those sentinels are what let an empty array, or a cut at either end, fall out of the same comparison with no special cases.
  5. If the cut is valid: odd total returns max(left_a, left_b); even total averages that with min(right_a, right_b).
  6. Otherwise move the cut toward the side that was too large and repeat.

Dry Run

Example 2, a = [1,2], b = [3,4]. Both have length 2, so no swap. total = 4, half = (4+1)/2 = 2, search range [0,2].

iteration 1:  cut = 1, other = half - cut = 1
  left_a = a[0] = 1    right_a = a[1] = 2
  left_b = b[0] = 3    right_b = b[1] = 4
  left_a <= right_b ?  1 <= 4   yes
  left_b <= right_a ?  3 <= 2   NO   -> b's left reaches too high
  we took too little from a, so search right:  lo = cut + 1 = 2

iteration 2:  cut = 2, other = 0
  left_a = a[1] = 2    right_a = none -> +inf
  left_b = none -> -inf    right_b = b[0] = 3
  left_a <= right_b ?  2 <= 3   yes
  left_b <= right_a ?  -inf <= +inf   yes   -> valid cut

  left half  = [1,2]   right half = [3,4]
  total is even, so average the boundary pair:
  (max(2, -inf) + min(+inf, 3)) / 2  =  (2 + 3) / 2  =  2 (floored)

Two iterations on a four-element input, and note that the first guess was wrong — the useful part of the trace is watching the invariant reject it.

Complexity

  • Time — O(log(min(m,n))): one binary search over the shorter array's cut positions, with constant work per step. Strictly better than the O(log(m+n)) the problem asks for. For contrast, the concatenate-and-sort opener is O((m+n) log(m+n)) and the two-pointer merge is O(m+n).
  • Space — O(1): four boundary values and two search bounds, no merged array. This is the other prize for not merging: the O(m+n) approach needs O(m+n) space unless you are careful to count rather than materialise.

Common Pitfalls

  • Binary searching the longer array. It still terminates, but other = half - cut can then fall outside b, and you inherit index checks that the swap removes for free.
  • Using half = (m + n) / 2. With an odd total the extra element then sits on the right, and max(left_a, left_b) is no longer the median. The +1 is doing real work.
  • Comparing left_a with left_b, or right_a with right_b. The invariant is strictly cross-wise: each left against the opposite right.
  • Omitting the infinity sentinels and hand-writing the empty-array and cut-at-the-edge cases. That is where most attempts at this problem actually break — one of the two inputs being empty is a legal input here.
  • Flooring a negative average by truncation. The answer wanted is the floor, and in Java and C++ integer division rounds toward zero, so (-4 + -3) / 2 gives -3 rather than the -4 required. Use Math.floorDiv, or correct the negative case by hand; Python's // already floors.

Full Solution — all languages

class Solution:
    # Sentinels stand in for a missing neighbour at either edge, which is what
    # lets an empty array and a cut at position 0 or m share the same branch.
    NEG, POS = -10 ** 18, 10 ** 18

    def findMedianSortedArrays(self, a, b):
        if len(a) > len(b):                      # always binary search the shorter one
            a, b = b, a
        shorter, longer = len(a), len(b)
        total = shorter + longer
        if total == 0:
            return 0
        half = (total + 1) // 2                  # +1 keeps the odd extra on the left
        lo, hi = 0, shorter
        while lo <= hi:
            cut = lo + (hi - lo) // 2            # elements taken from a
            other = half - cut                   # ... which forces the count from b
            left_a = a[cut - 1] if cut > 0 else self.NEG
            right_a = a[cut] if cut < shorter else self.POS
            left_b = b[other - 1] if other > 0 else self.NEG
            right_b = b[other] if other < longer else self.POS
            if left_a <= right_b and left_b <= right_a:
                if total % 2 == 1:
                    return max(left_a, left_b)
                # // already floors toward negative infinity in Python
                return (max(left_a, left_b) + min(right_a, right_b)) // 2
            if left_a > right_b:
                hi = cut - 1                     # took too much from a
            else:
                lo = cut + 1                     # took too little
        return 0
SensAI
Beta
Tap the mic to stop voice mode