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)).
Example 1:
Input: nums1 = [1,3], nums2 = [2] Output: 2.00000 Explanation: merged array = [1,2,3] and median is 2.
Example 2:
Input: nums1 = [1,2], nums2 = [3,4] Output: 2.50000 Explanation: merged array = [1,2,3,4] and median is (2 + 3) / 2 = 2.5.
Constraints:
nums1.length == mnums2.length == n0 <= m <= 10000 <= n <= 10001 <= m + n <= 2000-106 <= nums1[i], nums2[i] <= 106When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:
Imagine you have two separate groups of items, both already arranged in order from smallest to largest, and you want to find the exact middle value. The brute force approach involves gathering everything into one single giant pile, sorting the entire combined pile from scratch, and then locating the item sitting right in the middle.
Here's how the algorithm would work step-by-step:
class Solution:
def findMedianSortedArrays(self, nums1: list[int], nums2: list[int]) -> float:
combined_workspace = []
# Combine both sorted groups into a single workspace to prepare for sorting all elements together
for current_number in nums1:
combined_workspace.append(current_number)
for current_number in nums2:
combined_workspace.append(current_number)
# Sort the entire collection so that every single item is now in strict order from smallest to largest
combined_workspace.sort()
total_items_count = len(combined_workspace)
middle_index = total_items_count // 2
# Check if the total count is odd to locate the single median item directly in the middle
if total_items_count % 2 != 0:
return float(combined_workspace[middle_index])
# If the count is even, average the two middle items to find the exact halfway point
first_middle_item = combined_workspace[middle_index - 1]
second_middle_item = combined_workspace[middle_index]
return (first_middle_item + second_middle_item) / 2.0Instead of combining everything into one giant sorted list, the optimal approach treats the problem like balancing two stacked shelves of items by weight. By cleverly adjusting how much of each shelf we look at, we can quickly pinpoint the exact middle point without having to look at every single item.
Here's how the algorithm would work step-by-step:
class Solution:
def findMedianSortedArrays(self, nums1: list[int], nums2: list[int]) -> float:
if len(nums1) > len(nums2):
nums1, nums2 = nums2, nums1
total_length = len(nums1) + len(nums2)
half_length = total_length // 2
min_index = 0
max_index = len(nums1)
# We binary search the smaller array to find the correct partition point.
while min_index <= max_index:
partition_one = (min_index + max_index) // 2
partition_two = half_length - partition_one
left_one = float('-inf') if partition_one == 0 else nums1[partition_one - 1]
right_one = float('inf') if partition_one == len(nums1) else nums1[partition_one]
left_two = float('-inf') if partition_two == 0 else nums2[partition_two - 1]
right_two = float('inf') if partition_two == len(nums2) else nums2[partition_two]
# We check if left partitions are smaller than right partitions to validate the cut.
if left_one <= right_two and left_two <= right_one:
if total_length % 2 == 0:
return (max(left_one, left_two) + min(right_one, right_two)) / 2.0
else:
return float(min(right_one, right_two))
elif left_one > right_two:
max_index = partition_one - 1
else:
min_index = partition_one + 1
| Case | How to Handle |
|---|---|
| One or both input arrays are completely empty | Binary search partition logic safely handles empty arrays by treating them as having zero elements on that side. |
| Arrays of minimum size such as one element in each array | The partition bounds properly adjust to calculate the median using the single elements from both arrays. |
| Combined total number of elements is odd versus even | The algorithm checks the parity of the total length to return either the single middle element or the average of the two middle elements. |
| All elements in one array are smaller than all elements in the other array | Binary search correctly shifts the partition all the way to the left or right edge of the larger array. |
| Arrays contain highly skewed distributions with duplicate or identical values | Relies on relative ordering through binary search rather than distinct value counts, maintaining correct partition logic. |
| Inputs contain negative numbers, zeros, and extreme boundary values | Comparison operators handle signed numbers natively without requiring offset transformations or data normalization. |
| Maximum-sized input arrays pushing performance limits | Achieves strict logarithmic time complexity O(log(min(m, n))) by performing binary search only on the smaller array. |
| Floating point precision issues when calculating the median of two middle integers | Casts integer values to floating-point numbers before division to prevent integer truncation and maintain precision. |