☰ All problems

37. Median of Two Sorted Arrays

HardArrayBinary Search

You are given two arrays nums1 (length m) and nums2 (length n), each sorted in non-decreasing order. Return the median of all m + n numbers taken together.

The median is the middle value of the combined sorted sequence; when the total count is even, it is the average of the two middle values, so the answer can be fractional (answers within 10^-5 are accepted).

A merge gives O(m + n). Aim for O(log(min(m, n))).

Example 1
Input: nums1 = [1,4], nums2 = [2,7,9]
Output: 4.0

Explanation: Combined, the values are [1,2,4,7,9]; the middle one is 4.

Example 2
Input: nums1 = [1,3], nums2 = [2,4]
Output: 2.5

Explanation: Combined: [1,2,3,4], so the median is (2 + 3) / 2 = 2.5.

Example 3
Input: nums1 = [], nums2 = [5]
Output: 5.0

Constraints

  • 0 <= m, n <= 1000
  • 1 <= m + n <= 2000
  • -10^6 <= nums1[i], nums2[i] <= 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