DSA AnimatorDSA animations
Median of Two Sorted Arrays LC #4 Hard Binary Search · Partition
Problem

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

Example 1
Input: nums1 = [1,3], nums2 = [2]
Output: 2.0
Explanation: Merged: [1,2,3] → median = 2.0
Example 2
Input: nums1 = [1,2], nums2 = [3,4]
Output: 2.5
Explanation: Merged: [1,2,3,4] → median = (2+3)/2 = 2.5
Constraints: m, n ≥ 0  |  m + n ≥ 1  |  Both arrays sorted in non-decreasing order
Try Examples
Custom nums1: nums2:
Partition Visualization
A (nums1)
B (nums2)
maxLeft1
—
minRight1
—
maxLeft2
—
minRight2
—
maxLeft1 ≤ minRight2
maxLeft2 ≤ minRight1
—
Variables
lo
—
hi
—
i (part A)
—
j (part B)
—
max(maxL1,maxL2)
—
min(minR1,minR2)
—
Binary Search Range on i (0 … m)
Step Logic
Press ▶ Play or Next Step to begin the animation.
🎉
Ready
0 / 0
Select an example above and press Play.
Algorithm
1
Ensure A is the shorter array. Set lo=0, hi=m
2
Binary search: i = (lo+hi)/2, derive j = (m+n+1)/2 − i
3
Compute boundary: maxL1, minR1, maxL2, minR2 (use ±∞ at edges)
4
If maxL1 > minR2: i too large → hi = i−1
5
If maxL2 > minR1: i too small → lo = i+1
6
Valid partition → compute median from boundary elements
Time
O(log min(m,n))
Space
O(1)
Key Insight

We binary-search on partition index i in the shorter array A. For any i, we know exactly how many elements go into the left half from B: j = ⌊(m+n+1)/2⌋ − i.

The partition is valid when maxL1 ≤ minR2 and maxL2 ≤ minR1 — meaning the combined left side truly contains the ⌊(m+n)/2⌋ smallest elements.

For odd total: median = max(maxL1, maxL2).
For even total: median = (max(maxL1,maxL2) + min(minR1,minR2)) / 2.

How to solve Median of Two Sorted Arrays

LeetCode 4 · Hard · Binary Search · Pattern: Binary Search on Partition

Why the obvious approach is slow

Merging both arrays is O(m) plus n. Instead, we only need to find where the left half ends.

The key idea

Cut the shorter array at i and the longer one at j, so that the left side holds half of all numbers. The cut is correct when every number on the left is at most every number on the right. That means A left is at most B right, and B left is at most A right. Binary search i, and move it right when B left is too big, or left when A left is too big.

Remember

Binary search the cut, not the values. Left max at most right min means the cut is right.

Run the animation above on your own input, or watch the 1:36 video explanation of Median of Two Sorted Arrays with a dry run and Java code.

More Binary Search problems