AAlgoLoopSpaced repetition for LeetCode
HARDBinary SearchLeetCode ↗

Median of Two Sorted Arrays

The key idea

Don't merge — partition. Cut both arrays so the left halves together hold exactly half of all elements. The correct cut is the one where every left value is <= every right value; binary search the smaller array for that cut to hit O(log (m+n)).

Problem

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

The median is the middle value of the combined sorted order. When the total count m + n is odd, it is the single middle element; when it is even, it is the average of the two middle elements.

Constraints

Examples

Input: nums1 = [1,3], nums2 = [2] Output: 2.00000
Input: nums1 = [1,2], nums2 = [3,4] Output: 2.50000

Complexity

Time: O(log (m+n)) Space: O(1)

See the full solution

410310
Step-by-step visualization
Start free →

More Binary Search problems