Median of Two Sorted Arrays

HardBinary Search

You are given two arrays nums1 and nums2, each already sorted in ascending order. Return the median of all the numbers in both arrays combined: the middle value when everything is sorted, or the mean of the two middle values when the total count is even.

The result can be a half, such as 2.5, so return a number, not an integer (in Python use /, not //). Your solution should run in O(log(m + n)) time, which rules out merging the two arrays.

Constraints

  • 0 <= nums1.length, nums2.length <= 1000, and nums1.length + nums2.length >= 1
  • -10^6 <= nums1[i], nums2[i] <= 10^6
  • Both arrays are sorted in non-decreasing order.

Examples

Example 1

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

Merged: [1, 2, 3]. The median is the middle value, 2.

Example 2

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

Merged: [1, 2, 3, 4]. With an even count the median is the mean of the middle pair: (2 + 3) / 2 = 2.5.

Example 3

Input: nums1 = [], nums2 = [5]
Output: 5

One array may be empty.

JavaScript you'll use: Arrays: create, read, update Numbers, Math and integer tricks

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

Ctrl/⌘ + ' runs the examples, Ctrl/⌘ + Enter submits. Use console.log freely: output shows under Console. In the editor, press Esc then Tab to move focus out.