Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Find median of two sorted arrays

Compute the median of two sorted arrays in logarithmic time by binary searching the smaller array.

Python practice30 minSearching & SortingAdvancedLast updated March 25, 2026

Problem statement

Given two sorted arrays nums1 and nums2 of sizes m and n respectively, return the median of the two sorted arrays. The overall run time complexity should be O(log(min(m, n))). If the combined length is odd, return the middle element as a float. If even, return the average of the two middle elements as a float. Do not merge the arrays into a single sorted array — use binary search on partitions instead.

Task

Implement an O(log(min(m, n))) time algorithm to find the median of two sorted arrays without fully merging them.

Examples

Odd total length

Input

nums1 = [1, 3], nums2 = [2]

Output

2.0

Combined sorted array is [1,2,3]; median is 2.

Even total length

Input

nums1 = [1, 2], nums2 = [3, 4]

Output

2.5

Combined sorted array is [1,2,3,4]; median is (2+3)/2 = 2.5.

Input format

Two Python lists of numbers: nums1 and nums2 (both sorted ascending).

Output format

A single number (float) — the median of the combined arrays.

Constraints

0 <= m, n <= 10^5. Elements are comparable. Aim for O(log(min(m, n))) time and O(1) extra space.

Samples

Sample 1

Input

nums1 = [0, 0], nums2 = [0, 0]

Output

0.0

All elements are zero; median is 0.0.