Find Median of Two Sorted Arrays in Python
Merges two sorted arrays with a two-pointer walk and returns the median of the combined sorted sequence.
Python code
24 linesdef median_of_two_sorted_arrays(nums1, nums2):
merged = []
i = j = 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])
return (merged[n // 2 - 1] + merged[n // 2]) / 2.0
if __name__ == "__main__":
a = [1, 3, 8]
b = [2, 4, 5, 6]
print(median_of_two_sorted_arrays(a, b))
c = [1, 2]
d = [3, 4]
print(median_of_two_sorted_arrays(c, d))
Output
4.0
2.5
How it works
The algorithm performs a merge walk: it advances two pointers through the arrays, always appending the smaller current element to a merged list. After the merge, the median is found from the merged list — the middle element for odd length, or the average of the two middle elements for even length. This approach is straightforward and runs in O(n + m) time, using O(n + m) extra memory.
Common mistakes
- Using floor division on an even-length merged list without averaging the two middle values.
- Forgetting to extend the merged list with remaining elements from either array after the main loop.
- Assuming the arrays are not empty; the code does not handle empty inputs explicitly.
Variations
- Use a binary search approach for an O(log(min(n, m))) solution.
- Use `heapq.merge` to combine the arrays before computing the median.
Real-world use cases
- Calculating the median performance metric from two sorted log files in a monitoring system.
- Computing the median latency from two sorted data streams in real-time analytics pipelines.
- Finding a percentile boundary when merging sorted results from two database shards.
Sponsored
More from Algorithms & data structures
- Binary Search for Ship Capacity in Python medium
- Binary Search on Answer in Python: Koko Eating Bananas medium
- Bucket Numbers into Histogram Bin Counts in Python easy
- Container With Most Water: Two-Pointer Solution in Python medium
- Count Smaller Elements to the Right in Python easy
- Depth First Search Traversal Order in Python easy
Keep learning
Related tutorials and quizzes for this topic.