CodingNodes / Binary Search / Median of Two Sorted Arrays System design Space play · ←→ step · R restart

Problem

You are given two arrays of integers, nums1 and nums2, each already sorted from smallest to largest. Return the median of all their numbers put together.

The median is the middle number when everything is in order. If the total count is even there are two middle numbers, and the median is their average. Your solution should run in O(log(m + n)) time, where the arrays have m and n numbers.

Constraints

  • 0 ≤ nums1.length, nums2.length ≤ 1000
  • 1 ≤ nums1.length + nums2.length ≤ 2000
  • −10⁶ ≤ nums1[i], nums2[i] ≤ 10⁶
  • Both arrays are sorted in non-decreasing order

Examples: pick one to animate

Solutions

TimeO(log(min(m, n))) SpaceO(1)

Time: We binary search the cut position in the shorter array only, halving its range each step.

Space: Only a handful of integers are kept; nothing is merged or copied.

Cut both arrays so the left parts hold half of all numbers. The cut is right when the biggest number left of each cut is no larger than the smallest number right of the other cut. Binary search the cut in the shorter array; the cut in the longer one follows from the half-size rule. Missing neighbours count as plus or minus infinity.