Skip to content
Decoder

Median of Two Sorted Arrays

Hard

Problem

Given two sorted lists nums1 and nums2 (either may be empty, but not both), return the median of all their values combined. The median is the middle value of the merged order, or the average of the two middle values when the total count is even. Your solution must run in O(log(m + n)) time.

Example 1

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

Example 2

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

Example 3

Input
nums1 = [], nums2 = [1]
Output
1.0

Constraints

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

Read it once before you touch anything

Want some pressure? Start the timer. In an interview you get about two minutes to understand the problem.

  1. 1Read the goalWhat goes in, what comes out
  2. 2Scan the examplesCheck one by hand
  3. 3Note the constraintsThey set your Big O
Say what it asks in one sentence
Say it out loud first, then compare with ours.