InterviewPrepKit

Home / Coding / Binary Search

Median of Two Sorted Arrays

hard Original ↗
Solving tips
  • Recognize this as partition-finding, not element-finding: the median is just a valid split of the combined data into a left half of size (m+n+1)//2 and a right half where max(left) <= min(right).
  • Binary search the cut position i over the SHORTER array (swap first); j = half - i is then forced, so you only have one degree of freedom. A split is valid iff nums1[i-1] <= nums2[j] and nums2[j-1] <= nums1[i].
  • Use +/-infinity sentinels for out-of-range cuts (i=0, i=m, j=0, j=n) so empty-array and edge cases fall out for free.
  • Target O(log(min(m,n))) time, O(1) space; use (m+n+1)//2 (the +1) so the odd-length median lands in the left half and the odd case is simply max(left1,left2).

Problem

You are given two sorted integer arrays, nums1 (length m) and nums2 (length n). Return the median of all m + n numbers taken together, as a float.

The median of a sorted sequence is its middle element when the length is odd, and the average of the two middle elements when the length is even. The required time complexity is O(log(m + n)) — merging the arrays is not the intended answer.

Examples

  • nums1 = [1,3], nums2 = [2]2.0 Merged: [1,2,3]; the middle element is 2.
  • nums1 = [1,2], nums2 = [3,4]2.5 Merged: [1,2,3,4]; the two middle elements 2 and 3 average to 2.5.
  • nums1 = [], nums2 = [5]5.0 One array may be empty; the median comes entirely from the other.

Constraints

  • 0 <= m, n <= 1000 and 1 <= m + n <= 2000
  • -10^6 <= values <= 10^6
  • Required time: O(log(m + n)) — this is what makes the problem Hard.

Think about it first

Hint 1 The median splits the combined multiset into a left part and a right part of known sizes, where everything on the left is ≤ everything on the right. You don't need the merged array — only that split.
Hint 2 Any left part of total size `(m + n + 1) // 2` is formed by taking some prefix of `nums1` (say `i` elements) and a prefix of `nums2` (then forced to be `(m + n + 1) // 2 - i` elements). Only one value of `i` makes the split valid. What condition makes a split valid, and can you check it in O(1)?
Hint 3 Binary search on `i` over the shorter array. The split is valid when `nums1[i-1] <= nums2[j]` and `nums2[j-1] <= nums1[i]` (treat out-of-range as ±infinity). If `nums1[i-1] > nums2[j]`, the cut in `nums1` is too far right — shrink; otherwise grow. The median then comes from the max of the left parts (and, for even totals, the min of the right parts).
Your workspace Not runnable by design — this is your interview scratchpad. Saved on this device.