LeetCode #4 Hard

Median of Two Sorted Arrays

Median of Two Sorted Arrays is LeetCode 4 (Hard). Given two sorted arrays nums1 (length m) and nums2 (length n), return the median of all m + n values taken together.

  • The median is the middle value of the combined sorted list, or the average of the two middle values when m + n is even.
  • One of the arrays may be empty, but not both.
  • The required running time is O(log(m + n)), so merging the two arrays, which is O(m + n), is not the intended answer.
Constraints
  • nums1.length == m
  • nums2.length == n
  • 0 <= m <= 1000
  • 0 <= n <= 1000
  • 1 <= m + n <= 2000
  • -10⁶ <= nums1[i], nums2[i] <= 10⁶
binary-searcharraydivide-and-conquer
Open on LeetCode ↗
02

Intuition

The median splits all the values into a left half and a right half of the same size. You never need to build that combined list. You only need to know how many values each array gives to the left half.

If nums1 gives its first i values, nums2 must give its first j = half - i. Both arrays are sorted, so the split is correct exactly when two border checks pass: the last left value of nums1 is at most the first right value of nums2, and the last left value of nums2 is at most the first right value of nums1. A failed check also tells you which way to move i, so i can be found by binary search.

How to spot this pattern

Two sorted arrays and an order statistic (median, k-th smallest) with a logarithmic time limit means you binary search a split point, not a value. The sorted order is what lets one comparison discard half of the remaining splits.

03

Approach

Try it first

Before reading on, take [1, 3, 8, 9, 15] and [7, 11, 18, 19, 21, 25]. The left half must hold 6 values. If the first array gives 2 of them, which values sit on each side of the two cuts, and is that split valid? Aim for O(log min(m, n)).

1

Search the shorter array

Swap the inputs if needed so that nums1 is the shorter one. Then j = half - i stays between 0 and n for every cut i from 0 to m, and the search takes O(log min(m, n)) steps.

2

Fix the size of the left half

Set half = (m + n + 1) // 2. The + 1 gives the left half the extra value when the total is odd, so the median is then simply the largest value on the left.

3

Try a cut and read its four border values

With lo = 0 and hi = m, pick i = (lo + hi) // 2 and j = half - i. Read left1 = nums1[i - 1], right1 = nums1[i], left2 = nums2[j - 1] and right2 = nums2[j]. A side with no value gets −∞ (on the left) or +∞ (on the right), so it can never fail a check.

4

Move the cut toward the valid split

If left1 > right2, nums1 gave too many values, so set hi = i - 1. If left2 > right1, it gave too few, so set lo = i + 1. If neither, every left value is at most every right value and the split is correct.

5

Read the median from the borders

For an odd total, the median is max(left1, left2), the largest value on the left. For an even total, it is the average of max(left1, left2) and min(right1, right2), the two values that meet in the middle.

6

Why the search always lands on a valid cut

As i grows, left1 can only grow and right2 can only shrink, so the check left1 > right2 switches from false to true at most once. Likewise left2 > right1 can only switch from true to false. The cut taken from the real merged order passes both, and every failed check points toward it.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def findMedianSortedArrays(self, nums1, nums2):
▶3 if len(nums1) > len(nums2):
▶4 nums1, nums2 = nums2, nums1
▶5 m, n = len(nums1), len(nums2)
▶6 half = (m + n + 1) // 2
▶7 lo, hi = 0, m
▶8 while lo <= hi:
▶9 i = (lo + hi) // 2
▶10 j = half - i
▶11 left1 = nums1[i - 1] if i > 0 else float("-inf")
▶12 right1 = nums1[i] if i < m else float("inf")
▶13 left2 = nums2[j - 1] if j > 0 else float("-inf")
▶14 right2 = nums2[j] if j < n else float("inf")
▶15 if left1 > right2:
▶16 hi = i - 1
▶17 elif left2 > right1:
▶18 lo = i + 1
▶19 else:
▶20 if (m + n) % 2:
▶21 return max(left1, left2)
▶22 return (max(left1, left2) + min(right1, right2)) / 2
shorter138915longer71118192125border checksleft1 ≤ right2left2 ≤ right1swap: nums2 is shorter → the left half needs 6 values
m, n5, 6after the swap
half6size of the left half
cuts to try0 to 5
nums2 is the shorter array, so the two are swapped and the search runs over it. There are 11 values in total, so the left half holds 6, one more than the right. The search only decides how many of them come from the shorter array: anything from 0 to 5.
shorter138915left1right1longer71118192125left2right2border checksleft1 ≤ right2left2 ≤ right1try 2 from the shorter, 4 from the longer
lo, hi0, 5cuts still possible
i2middle of the range
j46 − 2
Cut the shorter array after 2 values, the middle of the cuts still possible (0 to 5). The longer array must then give 6 − 2 = 4 so the left half has 6 values.
shorter138915left1right1longer71118192125left2right2border checks3≤21okleft1 ≤ right219>8failsleft2 ≤ right1left2 too big → take more from the shorter
left1, right13, 8
left2, right219, 21
next range3 to 5
19 sits on the left but is bigger than 8 on the right, so the shorter array gave too few. Every cut from 2 down is ruled out.
shorter138915left1right1longer71118192125left2right2border checksleft1 ≤ right2left2 ≤ right1try 4 from the shorter, 2 from the longer
lo, hi3, 5cuts still possible
i4middle of the range
j26 − 4
Cut the shorter array after 4 values, the middle of the cuts still possible (3 to 5). The longer array must then give 6 − 4 = 2 so the left half has 6 values.
shorter138915left1right1longer71118192125left2right2border checks9≤18okleft1 ≤ right211≤15okleft2 ≤ right1both checks pass → the split is right
left1, right19, 15
left2, right211, 18
next rangedone
Every left value is at most every right value: 9 ≤ 18 and 11 ≤ 15. So the green tiles are exactly the smallest 6 values.
shorter138915left1right1longer71118192125left2right2median911→11left1left2the largeranswer: 11
median11max of the left borders
The total is odd and the left half got the extra value, so the median is the largest value on the left: max(9, 11) = 11.
05

Merge up to the middle

Take the smaller front value of the two arrays, one at a time, exactly as merge sort would, but stop once the middle is reached. Only the last two values taken are kept: the last one is the median for an odd total, and the last two are averaged for an even total.

▶1class Solution:
▶2 def findMedianSortedArrays(self, nums1, nums2):
▶3 m, n = len(nums1), len(nums2)
▶4 total = m + n
▶5 i = j = 0
▶6 prev = cur = 0
▶7 for _ in range(total // 2 + 1):
▶8 prev = cur
▶9 if j == n or (i < m and nums1[i] <= nums2[j]):
▶10 cur = nums1[i]
▶11 i += 1
▶12 else:
▶13 cur = nums2[j]
▶14 j += 1
▶15 return cur if total % 2 else (prev + cur) / 2
06

Common pitfalls

Binary searching the longer array

✗ Wrong
m, n = len(nums1), len(nums2)
lo, hi = 0, m
✓ Right
if len(nums1) > len(nums2):
    nums1, nums2 = nums2, nums1

When the searched array is longer than half the total, some cuts give a negative j. On [1, 2, 3, 4, 5, 6, 7] and [8] the search tries i = 5, so j = -1, and Python's nums2[j - 1] quietly reads from the end of the array and the result is 5.5 instead of 4.5. C++ and Java read out of bounds.

Averaging with integer division

✗ Wrong
return (max(left1, left2) + min(right1, right2)) / 2;
✓ Right
return (max(left1, left2) + (double) min(right1, right2)) / 2.0;

In C++ and Java, dividing two ints drops the fraction. On [1, 2] and [3, 4] the median is 2.5, but integer division returns 2.

Leaving the extra value on the right

✗ Wrong
half = (m + n) // 2
✓ Right
half = (m + n + 1) // 2

With an odd total, the middle value then lands on the right side, so max(left1, left2) is one place too early. On [1, 3] and [2] this returns 1 instead of 2.

07

Edge cases

One array is empty, such as [] and [1]

After the swap the empty array is nums1, so the only cut is i = 0 and both of its borders are infinite. The checks pass at once and the median comes from nums2 alone.

08

Complexity

Time
O(log min(m, n))
Space
O(1)
Each round halves the range of cuts in the shorter array, which has min(m, n) + 1 possible cuts. Only a few indexes and border values are stored.
09

Median of Two Sorted Arrays FAQ

How is this related to the k-th smallest element of two sorted arrays?

The median is the k-th smallest value with k = (m + n + 1) / 2, averaged with the next one when the total is even. A k-th element search compares the k/2-th value of each array and throws away the smaller side's first k/2 values, which runs in O(log(m + n)). The cut search here does the same job without recursion.

Does it still work when the arrays share values?

Yes. The checks use <=, so equal values on both sides of a cut are allowed. On [1, 1] and [1, 1] the first cut tried already passes and the median is 1.