This is LeetCode #4: Median of Two Sorted Arrays — one of the hardest problems on LeetCode! This is the boss battle. 🏆
💡 Think of it like this: You have two sorted lists of numbers. If you merged them into one big sorted list, what would the middle number be? The challenge: do it in O(log(m+n)) time, not O(m+n).
The Key Insight — Binary Search on Partition:
Instead of merging, we find a cut point in each array that divides all numbers into a left half and right half, where left half ≤ right half and both halves have equal size.
💭 Your turn! Take what you learned above and write the code yourself. Struggling is part of learning! 🧠
Complexity: Time O(log(min(m,n))) — binary search on the shorter array. Space O(1). This is the required optimal solution.
def findMedian(nums1, nums2):
# Always binary search on the shorter array
A, B = nums1, nums2
if len(A) > len(B):
A, B = B, A
total = len(A) + len(B)
half = total // 2
lo, hi = 0, len(A) - 1
while True:
i = (lo + hi) // 2 # Cut in A
j = half - i - 2 # Cut in B
a_left = A[i] if i >= 0 else float('-inf')
a_right = A[i+1] if i+1 < len(A) else float('inf')
b_left = B[j] if j >= 0 else float('-inf')
b_right = B[j+1] if j+1 < len(B) else float('inf')
if a_left <= b_right and b_left <= a_right: # Valid!
if total % 2: # Odd
return min(a_right, b_right)
return (max(a_left, b_left) + min(a_right, b_right)) / 2
elif a_left > b_right:
hi = i - 1 # Move left in A
else:
lo = i + 1 # Move right in A
findMedianSortedArrays([1,3], [2])
2
findMedianSortedArrays([1,2], [3,4])
2.5