Median of Two Sorted Arrays

HardBinary Search · Partition🧩 Binary SearchLeetCode #4 ↗Updated

Problem

You get two arrays nums1 (size m) and nums2 (size n), each sorted in ascending order. Return the median of all m + n values taken together (average of the two middle values when the total is even). The target running time is O(log(m + n)).
Input[1,3], [2]Output2.0
Input[1,2], [3,4]Output2.5

0 ≤ m, n ≤ 1000  ·  1 ≤ m + n ≤ 2000  ·  -106 ≤ nums[i] ≤ 106  ·  Required: O(log(m+n)) time.

Try it yourself

Java
class Solution {
    public double findMedianSortedArrays(int[] nums1, int[] nums2) {
        
    }
}
Your code is saved in this browser.Submit on LeetCode ↗
Key insight
The median splits the merged data into a left half and a right half. Choosing how many elements i come from nums1 fixes the count from nums2 (j = half - i), so we only binary search one cut in the shorter array until left max ≤ right min on both sides.
PatternBinary Search

Instinct Sorted data, a rotated array, or find the min/max X that works where a yes/no test flips only once - halve the search space every step.

Memory hack Find the fence - every candidate reads NO NO NO YES YES, and binary search just walks to where the fence stands.

Open the Binary Search guide →

Approaches

Brute ForceConcatenate & Sort

Time O((m+n) log(m+n))Space O(m+n)

Ignore that the inputs are sorted: copy both into one array, sort it, and read the middle element(s). Correct, but it throws away the sortedness we were given.

Java
public double findMedianSortedArrays(int[] nums1, int[] nums2) {
    int[] all = new int[nums1.length + nums2.length];
    System.arraycopy(nums1, 0, all, 0, nums1.length);
    System.arraycopy(nums2, 0, all, nums1.length, nums2.length);
    Arrays.sort(all);
    int n = all.length;
    if (n % 2 == 1) return all[n / 2];
    return (all[n / 2 - 1] + all[n / 2]) / 2.0;
}

Trivial to write, but wastes both the sorted input and extra memory.

At a glance

LevelApproachTimeSpace
Brute ForceConcatenate & SortO((m+n) log(m+n))O(m+n)
BetterMerge Walk to the MiddleO(m+n)O(1)
OptimalBinary Search on the PartitionO(log min(m,n))O(1)
Common pitfalls
  • Binary searching the longer array — py can fall out of range.
  • Integer division for the even case — divide by 2.0 (or cast) to keep the .5.
  • Forgetting empty sides: use ±∞ sentinels when a cut is at 0 or the end.
Interview tips
  • Start with the merge walk, then ask: “do we need every element before the middle?”
  • Explain the partition condition before coding; the code follows from it.
  • Using (m+n+1)/2 puts the extra element on the left, so odd totals return maxLeft.
Pattern
Binary search on a partition / answer → k-th element across sorted sources in logarithmic time.
My notes saved in this browser