InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Binary Search

Median of Two Sorted Arrays

hard Original ↗ 00:00

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).

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug