1. Understand the Problem

Given two arrays, nums1 and nums2, both sorted in ascending order, return the median of all their elements.

The median is:

Example 1: Odd number of elements

nums1 = [1, 3]
nums2 = [2]

# Combined array: [1, 2, 3]
# Median: 2.0

Example 2: Even number of elements

nums1 = [1, 2]
nums2 = [3, 4]

# Combined array: [1, 2, 3, 4]
# Median: (2 + 3) / 2 = 2.5

2. Signal

Look for these clues:

These clues suggest two approaches:

  1. Brute force: Merge the arrays into one sorted array and calculate its median.
  2. Optimized: Use binary search to find a valid partition between the arrays.

3. Edge Cases

Case Example Expected result
One array is empty nums1 = [], nums2 = [1] 1.0
Total length is odd [1, 3], [2] 2.0
Total length is even [1, 2], [3, 4] 2.5
Arrays contain negative numbers [-5, -3], [-2, 0] -2.5
All elements in one array are smaller [1, 2], [3, 4] 2.5
Arrays have different lengths [1], [2, 3, 4, 5, 6] 3.5