Median of Two Sorted Arrays (LeetCode 4): Solution and Explanation

Hard
Array
Binary Search
Divide And Conquer

Given two sorted arrays, return the median of all their elements combined, as if they were merged into one sorted array. The target running time is logarithmic in the array sizes.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

Intuition

The direct approach merges the two arrays with two pointers, like the merge step of merge sort, and reads the middle element or elements. That is O(m + n). You can stop the merge halfway, but it is still linear. To get to logarithmic time you have to avoid building the merged array at all.

Think about what the median really means. It splits the combined elements into a left half and a right half of equal size (or with one extra on the right for odd totals), where everything on the left is at most everything on the right. That left half is made of some prefix of A and some prefix of B. If you take i + 1 elements from A, you must take exactly half - (i + 1) elements from B. So choosing the cut in A determines the cut in B, and the problem becomes finding the right single cut.

A cut is valid when the largest left value of A is at most the smallest right value of B, and the largest left value of B is at most the smallest right value of A. If A's left side is too big (Aleft > Bright), you took too many from A, so move the cut left. Otherwise you took too few, so move it right. That is a binary search on the cut position in A, and running it on the shorter array keeps it at O(log(min(m, n))) and keeps the B index in range.

Empty sides are handled with infinities: a cut before the first element has a left value of negative infinity, and a cut after the last has a right value of positive infinity. Once the cut is valid, the median is the smaller right value for an odd total, or the average of the larger left value and the smaller right value for an even total.

Approach: Binary search on the partition

  1. Let A be the shorter array and B the longer, and compute total and half = total // 2.
  2. Binary search over i, the index of the last element of A in the left half, with l = 0 and r = len(A) - 1.
  3. Set j = half - (i + 1) - 1, the last index of B in the left half.
  4. Read Aleft, Aright, Bleft and Bright, substituting negative or positive infinity when an index is out of range.
  5. If Aleft <= Bright and Bleft <= Aright, the partition is valid: return min(Aright, Bright) for an odd total, or the average of max(Aleft, Bleft) and min(Aright, Bright) for an even total.
  6. If Aleft > Bright, move left with r = i - 1; otherwise move right with l = i + 1.

Step-by-step example

nums1 = [1,2], nums2 = [3,4]
  1. Both arrays have length 2, so no swap happens. total = 4 and half = 2.
  2. First guess: i = 0, so j = 2 - 1 - 1 = 0. Aleft = 1, Aright = 2, Bleft = 3, Bright = 4.
  3. Bleft = 3 is greater than Aright = 2, so too few elements came from A. Move right with l = 1.
  4. Next i = 1 and j = -1. Aleft = 2, Aright = +∞, Bleft = -∞, Bright = 3. Both conditions hold.
  5. The total is even, so the median is (max(2, -∞) + min(+∞, 3)) / 2 = (2 + 3) / 2 = 2.5.

Code: Python, Java, C++

1class Solution:
2    def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float:
3        A, B = nums1, nums2
4        total = len(nums1) + len(nums2)
5        half = total // 2
6        
7        if len(B) < len(A):
8            A, B = B, A
9            
10        l, r = 0, len(A) - 1
11        while True:
12            i = (l + r) // 2
13            j = half - (i + 1) - 1
14            
15            Aleft = A[i] if i >= 0 else float("-infinity")
16            Aright = A[i + 1] if (i + 1) < len(A) else float("infinity")
17            Bleft = B[j] if j >= 0 else float("-infinity")
18            Bright = B[j + 1] if (j + 1) < len(B) else float("infinity")
19            
20            if Aleft <= Bright and Bleft <= Aright:
21                if total % 2:
22                    return min(Aright, Bright)
23                return (max(Aleft, Bleft) + min(Aright, Bright)) / 2
24            elif Aleft > Bright:
25                r = i - 1
26            else:
27                l = i + 1

Time and space complexity

Time

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

The binary search runs only over the shorter array, and each step does constant work to compute the cut in the longer one.

Space

O(1)

Only indices and four boundary values are stored.

Other approaches

Two-pointer merge (time O(m + n), space O(1))

Walk both arrays with two pointers as in merge sort and stop when you reach the middle position, tracking the last one or two values seen. It is easy to get right and is fine when linear time is acceptable.

K-th element by elimination (time O(log(m + n)), space O(log(m + n)))

Find the k-th smallest element of the union recursively by comparing the k/2-th elements of each array and discarding the smaller half. Calling it once or twice gives the median. It generalizes to any order statistic.

Common mistakes

  • Binary searching on the longer array, which can push j out of range and makes the boundary handling much harder.
  • Forgetting the infinity sentinels for cuts at the very start or end of an array, which leads to index errors on inputs like one empty array.
  • Using the wrong side for an odd total. With half = total // 2 elements on the left, the extra element is on the right, so the median is min(Aright, Bright).
  • Computing the midpoint with truncating division. When r drops to -1, the code needs i = -1, meaning A contributes nothing to the left half. Python's // floors to -1, but plain integer division in Java or C++ gives 0, which is why those versions call floor explicitly.

Frequently asked questions

Why do we binary search on the smaller array?

It limits the search to O(log(min(m, n))) steps and guarantees that the matching cut in the larger array always lands within its bounds.

How does the partition approach find the median?

It looks for a cut in each array so the combined left side has half the elements and every value on the left is at most every value on the right. The median then comes from the values adjacent to the cut.

Can I just merge the arrays?

Merging gives the right answer in O(m + n) time and is a reasonable first solution. The logarithmic partition method is what an interviewer expects for this hard problem.

What happens if one array is empty?

The empty array becomes A, its cut values are all infinities, and the condition holds right away. The median is then read directly from the middle of the other array.