Median of Two Sorted Arrays

Hard Binary Search AI round

nums1 and nums2 are two lists of whole numbers, each sorted from smallest to largest. Either may be empty, but not both.

The median of all their numbers together is the middle number once they are put in order, or, when there is an even count of them, the average of the two middle numbers.

Return that median. It is a decimal, not rounded to a whole number; an answer within 10⁻⁵ of it is right.

Example 1

Input: nums1 = [2,9,14], nums2 = [5,11]
Output: 9

Together, in order, the numbers are 2, 5, 9, 11, 14. There are five, so the median is the third, 9.

Example 2

Input: nums1 = [-9,6,20], nums2 = [-4,2,2]
Output: 2

Example 3

Input: nums1 = [], nums2 = [7,8]
Output: 7.5

Constraints

  • 0 ≤ nums1.length, nums2.length ≤ 10⁵
  • 1 ≤ nums1.length + nums2.length
  • -2³¹ ≤ nums1[i], nums2[i] ≤ 2³¹ - 1
  • nums1 and nums2 are each sorted from smallest to largest, and may repeat numbers

Watch the explanation

More Binary Search

All Binary Search problems