Skip to content

Median of Two Sorted Arrays

Find the median of two sorted arrays in logarithmic time by binary searching a split of the shorter one.

HardBinary Search
Solve on LeetCode

The problem

You get two sorted integer arrays nums1 and nums2 of sizes m and n, and at least one of them is non-empty. Return the median of all m + n numbers taken together: the middle value, or the average of the two middle values when the total count is even. The intended solution runs in O(log(m + n)) time.

Input nums1 = [2, 6, 9], nums2 = [4, 10]

Output 6.00000

Merged, the numbers are 2, 4, 6, 9, 10, and the middle one is 6.

Input nums1 = [1, 3], nums2 = [5, 8]

Output 4.00000

Merged, the numbers are 1, 3, 5, 8, so the median is (3 + 5) / 2 = 4.

Key constraint: Merging takes O(m + n) time; the target is logarithmic, so you can't look at every number.

How to spot the pattern

  • Both arrays are sorted, and you only need the value at the middle of their merge.
  • The time limit is logarithmic, so you must binary search instead of merging.

The idea

Split both arrays into a left part and a right part so that the two left parts together hold half of all the numbers. The split is correct when every number on the left is at most every number on the right, which needs only two cross checks: left1 <= right2 and left2 <= right1. Binary search the split point i in the shorter array; the split in the other array follows from it, and if left1 > right2 you move i left, otherwise right.

Brute force: Merge the two arrays as in merge sort and read the middle, which takes O(m + n) time and space.

Step by step

  1. 1Make nums1 the shorter array, and let half = (m + n + 1) / 2, the size of the left part.
  2. 2Binary search i, the count taken from nums1, between 0 and m; then j = half - i come from nums2.
  3. 3Let left1 = nums1[i - 1], right1 = nums1[i], left2 = nums2[j - 1] and right2 = nums2[j], using minus or plus infinity when an index falls outside its array.
  4. 4If left1 > right2, move i left; if left2 > right1, move i right.
  5. 5Otherwise the split is right: the median is max(left1, left2) for an odd total, or the average of max(left1, left2) and min(right1, right2) for an even one.

See the pattern move

The binary search pattern on a small example. Step through it, or press play.

Code

class Solution:
    def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float:
        if len(nums1) > len(nums2):
            nums1, nums2 = nums2, nums1  # binary search the shorter array
        m, n = len(nums1), len(nums2)
        half = (m + n + 1) // 2  # size of the left part
        lo, hi = 0, m
        while lo <= hi:
            i = lo + (hi - lo) // 2  # numbers taken from nums1
            j = half - i  # numbers taken from nums2
            left1 = nums1[i - 1] if i > 0 else float("-inf")
            right1 = nums1[i] if i < m else float("inf")
            left2 = nums2[j - 1] if j > 0 else float("-inf")
            right2 = nums2[j] if j < n else float("inf")
            if left1 > right2:
                hi = i - 1  # took too many from nums1
            elif left2 > right1:
                lo = i + 1  # took too few from nums1
            elif (m + n) % 2 == 1:
                return float(max(left1, left2))
            else:
                return (max(left1, left2) + min(right1, right2)) / 2
        return 0.0  # not reached when both arrays are sorted

Complexity

Time

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

Space

O(1)

The binary search runs over the shorter array only, and each step is a few comparisons; that is within the O(log(m + n)) target.

Watch out for

  • Searching the longer array: then j = half - i can go negative or past the end of the shorter one.
  • Forgetting the edges where one side of a split is empty; use minus or plus infinity for the missing neighbours.
  • Averaging with integer division: (3 + 4) / 2 must give 3.5, not 3.

Follow-up questions

How would you find the k-th smallest number of the two arrays?

Compare the (k/2)-th elements of both arrays and drop the first k/2 elements of the array whose element is smaller, since none of them can be the k-th; then repeat with a smaller k. That takes O(log k), and the median is the k-th smallest for k near (m + n) / 2.

Is the merge solution good enough?

It is correct and easy to explain, so it is a good first answer to say out loud, but it is O(m + n). The split search is what brings the time down to logarithmic.

In Hinglish

Chhote array mein cut ki jagah par binary search karo; dono left parts mein milake total ka aadha ho aur left ka max right ke min se bada na ho, toh median mil gaya.

Related problems