☰ All problems

Median of Two Sorted Arrays

HardArrayBinary Search

Two weather stations each keep a sorted list of their daily temperature anomalies, meaning how far each day was above or below normal, so values can be negative. nums1 holds m values and nums2 holds n values, both in non-decreasing order. A climate report needs the median of all m + n values taken together.

The median is the middle value of the combined sorted list. When m + n is even it is the average of the two middle values, so the answer can be fractional; answers within 10^-5 of the expected value are accepted.

Merging the two lists takes O(m + n) time. Aim for O(log(min(m, n))).

Example 1
Input: nums1 = [-3,4,10], nums2 = [1,6]
Output: 4.0

Explanation: Combined, the values are [-3,1,4,6,10], and the middle one is 4.

Example 2
Input: nums1 = [2,9], nums2 = [5,7,8,12]
Output: 7.5

Explanation: Combined: [2,5,7,8,9,12], so the median is (7 + 8) / 2 = 7.5.

Example 3
Input: nums1 = [], nums2 = [-6,-1]
Output: -3.5

Explanation: One station has no data, and the median of [-6,-1] is (-6 + -1) / 2 = -3.5.

Constraints

  • nums1 and nums2 each hold between 0 and 1000 values, and at least one of them is non-empty.
  • Every value is an integer from -10^6 to 10^6.
💡 Hint 1

The median splits the combined values into a left part and a right part of (almost) equal size, where everything on the left is <= everything on the right.

💡 Hint 2

If you take i elements from nums1 for the left part, the size forces you to take half - i from nums2. So only i needs to be chosen.

💡 Hint 3

Binary search i over the shorter array: check the four values around the cut. If nums1[i-1] > nums2[j], take fewer from nums1; if nums2[j-1] > nums1[i], take more.

/**
 * @param {number[]} nums1
 * @param {number[]} nums2
 * @return {number}
 */
function findMedianSortedArrays(nums1, nums2) {

}
Ctrl/⌘ + ' run · Ctrl/⌘ + Enter submit
esc