Skip to content

Median of Two Sorted Arrays

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)).

nums1nums2OutputExplanation
[1, 3][2]2.0Merged array: [1, 2, 3]. Median is 2.
[1, 2][3, 4]2.5Merged array: [1, 2, 3, 4]. Median is (2 + 3) / 2 = 2.5
[][1]1.0Single element
  • nums1.length == m
  • nums2.length == n
  • 0 <= m <= 1000
  • 0 <= n <= 1000
  • 0 <= nums1[i], nums2[j] <= 10^6
ApproachTimeSpaceBest When
Binary SearchO(log(min(m,n)))O(1)Optimal — logarithmic time
Two-PointerO(m + n)O(1)Simpler implementation
  • Pick Binary Search for the optimal O(log(min(m,n))) solution and interview preparation.
  • Pick Two-Pointer if you want a simpler approach to understand the concept first.
Optimal
Binary Search
O(log(min(m,n))) time · O(1) space
Simpler
Two-Pointer
O(m + n) time · O(1) space
★ Recommended

Use binary search on the shorter array to find the partition point where the left half equals the right half in total length. This achieves O(log(min(m,n))) time.

⏱ Time O(log(min(m,n))) Binary search 💾 Space O(1) Constant
median_sorted_arrays_binary_search.py
from typing import List
def findMedianSortedArrays(nums1: List[int], nums2: List[int]) -> float:
"""Binary search approach: O(log(min(m,n))) time, O(1) space"""
if len(nums1) > len(nums2):
return findMedianSortedArrays(nums2, nums1)
m, n = len(nums1), len(nums2)
left, right = 0, m
while left <= right:
partition1 = (left + right) // 2
partition2 = (m + n + 1) // 2 - partition1
left_max1 = float('-inf') if partition1 == 0 else nums1[partition1 - 1]
right_min1 = float('inf') if partition1 == m else nums1[partition1]
left_max2 = float('-inf') if partition2 == 0 else nums2[partition2 - 1]
right_min2 = float('inf') if partition2 == n else nums2[partition2]
if left_max1 <= right_min2 and left_max2 <= right_min1:
if (m + n) % 2 == 0:
return (max(left_max1, left_max2) + min(right_min1, right_min2)) / 2
else:
return max(left_max1, left_max2)
elif left_max1 > right_min2:
right = partition1 - 1
else:
left = partition1 + 1
return -1.0
🎯 Interview Favourite

Merge both arrays while keeping track of the middle elements. This is linear time but easier to understand.

⏱ Time O(m + n) Linear merge 💾 Space O(1) Constant
median_sorted_arrays_two_pointer.py
from typing import List
def findMedianSortedArrays(nums1: List[int], nums2: List[int]) -> float:
"""Two-pointer merge approach: O(m+n) time, O(1) space"""
merged = []
i, j = 0, 0
while i < len(nums1) and j < len(nums2):
if nums1[i] <= nums2[j]:
merged.append(nums1[i])
i += 1
else:
merged.append(nums2[j])
j += 1
merged.extend(nums1[i:])
merged.extend(nums2[j:])
n = len(merged)
if n % 2 == 1:
return float(merged[n // 2])
else:
return (merged[n // 2 - 1] + merged[n // 2]) / 2.0