DSA Explained
#4

Median of Two Sorted Arrays

Hard

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

💡 In plain English

Imagine two separate stacks of graded exam papers, both already arranged from lowest score to highest score. You want to find the median score of all students combined without combining all papers into one massive pile and re-sorting them! You only need to place a dividing knife across both stacks so that the left half has the same total number of papers as the right half, and every score on the left is lower than or equal to every score on the right. By doing binary search on just the smaller stack, you find the right cut in seconds!

Reference: LeetCode #4 • Median of Two Sorted Arrays

Select Viable ApproachCompare pointer scanning O(m+n) against binary search partitioning O(log(min(m, n)))
Execution Timeline (Binary Search Cut)

Median Cut Visualizer

Optimal: Binary Search on Partition
Step 1 / 6
1

Initialize Binary Search on Shorter Array

SEARCHING

We ensure nums1 is the shorter array (m = 3 <= n = 4). We search for the partition cut in nums1 within range [low = 0, high = 3]. Total elements = 7, so left half needs exactly (3 + 4 + 1) / 2 = 4 elements.

nums1 (m = 3)Binary Search TargetpartX = —
1
[0]
3
[1]
8
[2]
nums2 (n = 4)partY = —
7
[0]
9
[1]
10
[2]
11
[3]
Partition Boundary ValuesLeft vs Right
maxLeftX—
minRightX—
maxLeftY—
minRightY—
Condition & ActionVerdict
maxLeftX ≤ minRightY ( ≤ ):—
maxLeftY ≤ minRightX ( ≤ ):—
Binary search range: low = 0, high = 3. Target left-half count = 4.
1
function findMedianSortedArrays(nums1, nums2) {
2
if (nums1.length > nums2.length) {
3
return findMedianSortedArrays(nums2, nums1);
4
}
5
const m = nums1.length, n = nums2.length;
6
let low = 0, high = m;
7
while (low <= high) {
8
const partitionX = Math.floor((low + high) / 2);
9
const partitionY = Math.floor((m + n + 1) / 2) - partitionX;
10
const maxLeftX = partitionX === 0 ? -Infinity : nums1[partitionX - 1];
11
const minRightX = partitionX === m ? Infinity : nums1[partitionX];
12
const maxLeftY = partitionY === 0 ? -Infinity : nums2[partitionY - 1];
13
const minRightY = partitionY === n ? Infinity : nums2[partitionY];
14
if (maxLeftX <= minRightY && maxLeftY <= minRightX) {
15
if ((m + n) % 2 === 1) {
16
return Math.max(maxLeftX, maxLeftY);
17
}
18
return (Math.max(maxLeftX, maxLeftY) + Math.min(minRightX, minRightY)) / 2;
19
} else if (maxLeftX > minRightY) {
20
high = partitionX - 1;
21
} else {
22
low = partitionX + 1;
23
}
24
}
25
return 0;
26
}
Binary Search Cut • Synchronized Line TraceLine 6 of 26
→ Executing Statement:Initialize pointers on shorter array: let low = 0, high = m;

Why the Optimal Solution? (Deriving the Approach)

From full array merges to logarithmic partition cuts without extra memory.

Mental Model Progression
01. StartO(m + n) space

Full Array Merge

Combine both arrays into a single sorted array of size (m + n) and index directly into the middle.

02. Memory SavingO(1) space

Two-Pointer Counting

Simulate merging using two pointers up to (m + n) / 2 without creating a new array. Still takes O(m + n) time.

03. Key InsightPartition Concept

What is a Median?

A median splits a dataset into equal Left and Right halves where every element on Left is ≤ every element on Right.

04. ObservationOne Cut Deduces Other

Dependent Cuts

If we pick partitionX elements from nums1, we MUST pick partitionY = (m + n + 1)/2 - partitionX from nums2!

05. OptimalO(log(min)) ✓

Binary Search Cut

Binary search the cut in the shorter array! Check if maxLeft ≤ minRight. Each comparison cuts search space in half.

Complexity Analysis for Binary Search Cut

Time ComplexityO(log(min(m, n)))
Best Case: O(1)
Average Case: O(log(min(m, n)))
Worst Case: O(log(min(m, n)))

Binary search cuts the partition search space of the shorter array in half with every iteration. Since m <= n, at most log₂(m) steps are needed.

Space Complexity (Auxiliary)O(1)
Auxiliary Memory: O(1)

Only a constant number of integer pointers and boundary variables are maintained; no auxiliary array is allocated.

Two-Pointer Counting Approach

O(m + n) Time

Simulate the merge process using two pointers p1 and p2. Track the previous and current values until reaching step (m + n) / 2.

for (let count = 0; count <= Math.floor(total / 2); count++) {
  prev = curr;
  if (p1 < m && (p2 >= n || nums1[p1] <= nums2[p2])) {
    curr = nums1[p1++];
  } else {
    curr = nums2[p2++];
  }
}
Why it is inefficient:

While it saves memory by avoiding a full merged array, it still checks elements sequentially. For large arrays with up to 1,000,000 items, inspecting (m + n) / 2 elements fails the strict logarithmic requirement.

Optimal Approach: Binary Search on Partition

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

Binary search the partition cut in the shorter array nums1. The cut in nums2 is automatically derived: partitionY = (m + n + 1) / 2 - partitionX. Check if boundary conditions hold in O(1).

if (maxLeftX <= minRightY && maxLeftY <= minRightX) {
  if ((m + n) % 2 === 1) return Math.max(maxLeftX, maxLeftY);
  return (Math.max(maxLeftX, maxLeftY) + Math.min(minRightX, minRightY)) / 2;
} else if (maxLeftX > minRightY) {
  high = partitionX - 1;
} else {
  low = partitionX + 1;
}
Why it is optimal:

Each check cuts the binary search range in half. By always operating on the smaller array (m ≤ n), at most log₂(m) comparisons are ever performed, requiring only O(1) auxiliary variables.

Example Test Cases

Official LeetCode Examples
Example 1 (Odd Combined Length)
Input: nums1 = [1, 3], nums2 = [2]
Output: 2.00000
Merged array = [1, 2, 3] and median is 2.
Example 2 (Even Combined Length)
Input: nums1 = [1, 2], nums2 = [3, 4]
Output: 2.50000
Merged array = [1, 2, 3, 4] and median is (2 + 3) / 2 = 2.5.
Example 3 (One Empty Array)
Input: nums1 = [], nums2 = [1]
Output: 1.00000
When one array is empty, the median is simply the middle of the other array.

Rules & Limits

Constraints
  • Array lengths up to 1,000

    nums1.length == m, nums2.length == n, 0 ≤ m, n ≤ 1000, and 1 ≤ m + n ≤ 2000.

  • Wide value ranges

    -10⁶ ≤ nums1[i], nums2[i] ≤ 10⁶. Use appropriate integer infinity sentinels.

  • Always sorted

    Both input arrays are guaranteed to be sorted in non-decreasing order.

  • Floating-point output

    Return the answer as a 64-bit floating-point number (double).

Key Takeaways & Interview Mental Models

Binary Search on Answer Space
1. Always Search Shorter Array

If nums1.length > nums2.length, immediately return findMedian(nums2, nums1). This guarantees partitionY ≥ 0 and optimizes the binary search runtime to O(log(min(m, n))).

2. Virtual Infinity Sentinels

When the cut falls at index 0 or index m, use -Infinity and +Infinity. This elegantly handles boundary edges without writing dozens of messy if statements.

3. Binary Search on a Cut, Not a Value

This problem teaches an essential senior interview pattern: binary search does not have to search for a specific item in an array; it can search for an optimal partition boundary that balances two conditions.