Maintained by Vikas Dulgunde, software engineer
You are handed two arrays, nums1 and nums2. Each one is sorted in non-decreasing order on its own, but they are kept separate. Picture them merged into a single sorted list of every value from both. The median is the middle of that combined list.
When the combined length is odd, the median is the single middle value. When it is even, the median is the average of the two middle values, so the answer can be a fraction even when every input value is an integer.
The catch is the time budget. A naive merge runs in linear time, but the target is O(log(m+n)). That rules out walking through the elements and forces you to reason about where the median sits without ever building the merged list.
Either array may be empty, but their combined length is at least one, so a median always exists.
Combined and sorted the values are [1,2,3]. Three elements means one middle value, which is 2.
Combined the values are [1,2,3,4]. Four elements means the median is the average of the two middle values, (2 + 3) / 2 = 2.5.
One array is empty, so the merged list is just [1] and the only element is the median.
Merged the values are [1,2,3,4,5,6]. With six elements the median averages the two middle values, (3 + 4) / 2 = 3.5.
Visible test cases
The median splits the combined data into a left half and a right half of equal size, where every value on the left is no larger than every value on the right. You do not need the actual sorted order, only that split point.
Once you decide how many elements of nums1 fall into the left half, the count taken from nums2 is forced, because the two halves together must hold a fixed number of elements. So you are really searching for one number: how many elements to take from the shorter array.
Binary search that single number. For a candidate split, look at the largest value on the left of each array and the smallest value on the right of each array. The split is correct when both arrays' left maxima are no greater than both arrays' right minima.
Build the fully merged sorted sequence, then read the median straight out of the middle position.
Find a cut that divides the two arrays into a left group and a right group of equal size such that everything on the left is no larger than everything on the right. Binary search the cut position in the shorter array only.