Median of Two Sorted Arrays – Solution & Complexity
1. Think in Terms of a Partition
- The median splits the combined sorted values into a left half and a right half.
- Every value on the left must be less than or equal to every value on the right.
- If we can find that split without merging, we get logarithmic time.
2. Binary Search the Smaller Array
- Choose how many values come from
nums1on the left side, and infer how many must come fromnums2. - Searching the smaller array keeps the binary search range as small as possible and avoids invalid indexes.
- The left side should contain
(m + n + 1) // 2values so odd lengths put the median on the left.
3. Check the Partition Boundaries
- For a partition
iinnums1, usej = half - iinnums2. - Compare only four boundary values: left and right around each partition.
- Sentinels
-infandinfmake empty sides easy to handle.
4. Move Toward a Valid Split
- A partition is valid when
left1 <= right2andleft2 <= right1. - If
left1 > right2, too many values were taken fromnums1, so move left. - Otherwise, too few values were taken from
nums1, so move right.
5. Final Complete Solution
- For odd total length, the median is the largest value on the left side.
- For even total length, average the largest left value and smallest right value.
- Time complexity is O(log(min(m, n))), and extra space complexity is O(1).