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.

Easy Python 3.9+ Aug 9, 2026 Algorithms & data structures 16 views 0 copies

Python code

24 lines
Python 3.9+
def 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

stdout
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

  1. Use a binary search approach for an O(log(min(n, m))) solution.
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Algorithms & data structures

Related tutorials and quizzes for this topic.