#4

Median of Two Sorted Arrays

Hard Binary search on the partition

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

Return the median of two sorted arrays in O(log(m + n)).

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: the median of two sorted arrays combined, in O(log).

Why this works: cut both arrays so the left halves hold half of all numbers. The cut is right when every left number ≤ every right number. Binary search where to cut the smaller array.

Example: [1, 3] and [2]

cut A after 1 element, B after 1 → left {1, 2}, right {3}max(left) = 2 ≤ min(right) = 3 ✓odd total → median 2

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Binary searching the longer array, which makes j go out of range.

Solve on LeetCode ↗
Complexity
  • Time: O(log min(m, n)).
  • Space: O(1).
Topic: Binary Search
🎬 Episodes 21–23: video coming soon