Median of Two Sorted Arrays

Hard#4search the cut

You get two sorted arrays. Find the median of all their numbers together — the middle one, or the mean of the two middle ones for an even count — in O(log(m + n)) time. Our example: a = [1, 5, 9, 12, 20], b = [2, 3, 7, 10, 15, 18] — 11 numbers, the answer is 9.

input
nums1, nums2: two arrays of integers, each in non-decreasing order; one of them may be empty.
returns
The median of all their numbers together: the middle one, or the mean of the two middle ones if there is an even count. LeetCode wants it in O(log(m + n)).
constraints
  • 0 ≤ m = nums1.length ≤ 1000
  • 0 ≤ n = nums2.length ≤ 1000
  • 1 ≤ m + n
  • −10⁶ ≤ nums1[i], nums2[i] ≤ 10⁶
  • nums1 and nums2 are in non-decreasing order
our 15 tests keep to them
examples
Open a test in the tests panel: it shows the input and the expected answer.
/**
 * @param {number[]} nums1
 * @param {number[]} nums2
 * @return {number}
 */
function findMedianSortedArrays(nums1, nums2) {

}
Ctrl ↵
format
reset

saved in this browser

15 tests · limit 3 s

Stuck?

See the solution run step by step on our example, then why it works and its complexity.

Watch the walkthrough →

Next: more binary search problems

Pattern “Binary search” →

The problem and its statement belong to LeetCode. Here are our own retelling, example and solution. Patterns Hero is not affiliated with LeetCode.