Skip to content
CodeShare
All problems

Median of Two Sorted Arrays

Find the median of two sorted arrays combined.

HardArraysBinary search

Given two sorted arrays nums1 and nums2, return the median of the two arrays combined.

The median is the middle value of the combined sorted list, or the average of the two middle values when its length is even. Aim for O(log (m + n)) time.

Examples

Example 1
Input
nums1 = [1, 3], nums2 = [2]
Output
2
Why
Combined, the array is [1, 2, 3], so the median is 2.
Example 2
Input
nums1 = [1, 2], nums2 = [3, 4]
Output
2.5
Why
Combined, the array is [1, 2, 3, 4], so the median is (2 + 3) / 2 = 2.5.

Constraints

  • 0 <= nums1.length, nums2.length <= 1000
  • 1 <= nums1.length + nums2.length <= 2000
  • -10^6 <= nums1[i], nums2[i] <= 10^6