Browse curriculum

Median of Two Sorted Arrays (LeetCode 4)

Find the median of two sorted arrays in O(log min(m, n)) by binary searching where to cut the shorter array.

Problem Understanding

Median of Two Sorted Arrays: given two sorted arrays nums1 and nums2, return the median of all their numbers together, in O(log(m + n)) time.

Examples: [1, 3] and [2] give 2.0; [1, 2] and [3, 4] give (2 + 3) / 2 = 2.5.

Attempt 1: Merge, Then Pick the Middle

Merge the arrays as in Merge Two Sorted Lists and take the middle one or two values. That is O(m + n), and you only need to merge halfway, but it is still linear. The required log time means binary search, and the trick is choosing what to search.

The Intuition: Search the Cut, Not a Value

The median splits all the numbers into a smaller half and a larger half. Make that split with one cut in each array: take i numbers from A and j from B, with i + j = half, where half = (m + n + 1) / 2.

Once i is chosen, j is fixed. The cut is correct when every left number is ≤ every right number. Within each array that is already true, so only two cross checks remain:

  • A[i−1] ≤ B[j] and B[j−1] ≤ A[i] (treat values off the ends as −∞ or +∞).

If A[i−1] > B[j], too much was taken from A: move the cut left. If B[j−1] > A[i], too little: move it right. That monotone choice is exactly what binary search needs. On a valid cut, the median is the largest left value (odd total) or the average of the largest left and smallest right values (even total).

Median of Two Sorted Arrays Visualization

A IS THE SHORTER ARRAY · THE BARS ARE THE CUTS

SEARCH THE CUT IN A

A

2

0

B

1

0

3

1

i (cut A)

:

j (cut B)

:

Median

:

 

3 numbers, so the left half holds 2. Binary search where to cut the shorter array, A: anywhere from 0 to 1

Next

Cut A after 0 and B after 2 = 2 − 0. Around the cut: A −∞ | 2, B 3 | +∞

Free preview: the first 3 of 5 steps

nums1

nums2

Each array is drawn with a bar at its cut, and everything left of the bars is shaded: together, half of all the numbers. The four values touching the bars are the only ones compared; watch the cut in A move until both checks pass.

Median of Two Sorted Arrays Dry Run

Input: nums1 = [3, 4], nums2 = [1, 2]. A = [3, 4], B = [1, 2], half = 2.

lo hi i j A[i−1] | A[i] B[j−1] | B[j] Result
0 2 1 1 3 | 4 1 | 2 3 > 2: hi = 0
0 0 0 2 −∞ | 3 2 | +∞ valid

Even total: (max(−∞, 2) + min(3, +∞)) / 2 = 2.5.

Median of Two Sorted Arrays LeetCode Solution

Binary search the cut in the shorter array.

Median of Two Sorted Arrays Code
1var findMedianSortedArrays = function(nums1, nums2) {
2 if (nums1.length > nums2.length) [nums1, nums2] = [nums2, nums1];
3 const A = nums1, B = nums2;
4 const total = A.length + B.length, half = (total + 1) >> 1;
5 let lo = 0, hi = A.length;
6 while (lo <= hi) {
7 const i = (lo + hi) >> 1, j = half - i;
8 const aLeft = i > 0 ? A[i - 1] : -Infinity;
9 const aRight = i < A.length ? A[i] : Infinity;
10 const bLeft = j > 0 ? B[j - 1] : -Infinity;
11 const bRight = j < B.length ? B[j] : Infinity;
12 if (aLeft <= bRight && bLeft <= aRight) {
13 if (total % 2) return Math.max(aLeft, bLeft);
14 return (Math.max(aLeft, bLeft) + Math.min(aRight, bRight)) / 2;
15 }
16 if (aLeft > bRight) hi = i - 1;
17 else lo = i + 1;
18 }
19};

Median of Two Sorted Arrays in Python, Java, C++, TypeScript and C

Median of Two Sorted Arrays in Python
class Solution:
    def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float:
        A, B = (nums1, nums2) if len(nums1) <= len(nums2) else (nums2, nums1)
        total = len(A) + len(B)
        half = (total + 1) // 2
        lo, hi = 0, len(A)
        while lo <= hi:
            i = (lo + hi) // 2
            j = half - i
            a_left = A[i - 1] if i > 0 else float('-inf')
            a_right = A[i] if i < len(A) else float('inf')
            b_left = B[j - 1] if j > 0 else float('-inf')
            b_right = B[j] if j < len(B) else float('inf')
            if a_left <= b_right and b_left <= a_right:
                if total % 2:
                    return max(a_left, b_left)
                return (max(a_left, b_left) + min(a_right, b_right)) / 2
            if a_left > b_right:
                hi = i - 1
            else:
                lo = i + 1
Median of Two Sorted Arrays in Java
class Solution {
    public double findMedianSortedArrays(int[] nums1, int[] nums2) {
        if (nums1.length > nums2.length) return findMedianSortedArrays(nums2, nums1);
        int[] A = nums1, B = nums2;
        int total = A.length + B.length, half = (total + 1) / 2;
        int lo = 0, hi = A.length;
        while (lo <= hi) {
            int i = (lo + hi) / 2, j = half - i;
            int aLeft = i > 0 ? A[i - 1] : Integer.MIN_VALUE;
            int aRight = i < A.length ? A[i] : Integer.MAX_VALUE;
            int bLeft = j > 0 ? B[j - 1] : Integer.MIN_VALUE;
            int bRight = j < B.length ? B[j] : Integer.MAX_VALUE;
            if (aLeft <= bRight && bLeft <= aRight) {
                if (total % 2 == 1) return Math.max(aLeft, bLeft);
                return (Math.max(aLeft, bLeft) + (double) Math.min(aRight, bRight)) / 2;
            }
            if (aLeft > bRight) hi = i - 1;
            else lo = i + 1;
        }
        return 0;
    }
}
Median of Two Sorted Arrays in C++
class Solution {
public:
    double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
        if (nums1.size() > nums2.size()) return findMedianSortedArrays(nums2, nums1);
        vector<int>& A = nums1;
        vector<int>& B = nums2;
        int total = A.size() + B.size(), half = (total + 1) / 2;
        int lo = 0, hi = A.size();
        while (lo <= hi) {
            int i = (lo + hi) / 2, j = half - i;
            int aLeft = i > 0 ? A[i - 1] : INT_MIN;
            int aRight = i < (int)A.size() ? A[i] : INT_MAX;
            int bLeft = j > 0 ? B[j - 1] : INT_MIN;
            int bRight = j < (int)B.size() ? B[j] : INT_MAX;
            if (aLeft <= bRight && bLeft <= aRight) {
                if (total % 2) return max(aLeft, bLeft);
                return (max(aLeft, bLeft) + (double)min(aRight, bRight)) / 2;
            }
            if (aLeft > bRight) hi = i - 1;
            else lo = i + 1;
        }
        return 0;
    }
};
Median of Two Sorted Arrays in TypeScript
function findMedianSortedArrays(nums1: number[], nums2: number[]): number {
    if (nums1.length > nums2.length) [nums1, nums2] = [nums2, nums1];
    const A = nums1, B = nums2;
    const total = A.length + B.length, half = (total + 1) >> 1;
    let lo = 0, hi = A.length;
    while (lo <= hi) {
        const i = (lo + hi) >> 1, j = half - i;
        const aLeft = i > 0 ? A[i - 1] : -Infinity;
        const aRight = i < A.length ? A[i] : Infinity;
        const bLeft = j > 0 ? B[j - 1] : -Infinity;
        const bRight = j < B.length ? B[j] : Infinity;
        if (aLeft <= bRight && bLeft <= aRight) {
            if (total % 2) return Math.max(aLeft, bLeft);
            return (Math.max(aLeft, bLeft) + Math.min(aRight, bRight)) / 2;
        }
        if (aLeft > bRight) hi = i - 1;
        else lo = i + 1;
    }
    return 0;
}
Median of Two Sorted Arrays in C
double findMedianSortedArrays(int* nums1, int nums1Size, int* nums2, int nums2Size) {
    if (nums1Size > nums2Size) return findMedianSortedArrays(nums2, nums2Size, nums1, nums1Size);
    int total = nums1Size + nums2Size, half = (total + 1) / 2;
    int lo = 0, hi = nums1Size;
    while (lo <= hi) {
        int i = (lo + hi) / 2, j = half - i;
        int aLeft = i > 0 ? nums1[i - 1] : INT_MIN;
        int aRight = i < nums1Size ? nums1[i] : INT_MAX;
        int bLeft = j > 0 ? nums2[j - 1] : INT_MIN;
        int bRight = j < nums2Size ? nums2[j] : INT_MAX;
        if (aLeft <= bRight && bLeft <= aRight) {
            int left = aLeft > bLeft ? aLeft : bLeft;
            if (total % 2) return left;
            int right = aRight < bRight ? aRight : bRight;
            return (left + (double)right) / 2;
        }
        if (aLeft > bRight) hi = i - 1;
        else lo = i + 1;
    }
    return 0;
}

Edge Cases & Common Mistakes

  • One empty array: the search over the empty array has only i = 0, and the median comes from the other array.
  • Searching the longer array: j can go negative or past the end; always search the shorter one.
  • Forgetting the sentinels: a cut at either end has no neighbour on one side; use −∞ and +∞.
  • Odd totals: with half = (m + n + 1) / 2, the left side holds the extra element, so the median is the largest left value.

Summary

Cut the shorter array after i elements and the other after half − i. The cut is valid when A[i−1] ≤ B[j] and B[j−1] ≤ A[i]; otherwise move it left or right by binary search. The median comes from the four values around the cut. O(log min(m, n)) time, O(1) space.

More practice: DSA interview questions with answers · patterns cheat sheet

The approach, step by step

  1. Search the shorter array

    Let A be the shorter array, half = (m + n + 1) / 2, and binary search i from 0 to len(A); j = half − i.

  2. Check the four values at the cut

    Use −∞/+∞ off the ends. If A[i−1] > B[j], move left (hi = i − 1); if B[j−1] > A[i], move right (lo = i + 1).

  3. Read off the median

    On a valid cut: odd total, max(A[i−1], B[j−1]); even total, the average of that and min(A[i], B[j]).

Frequently asked questions

What is being binary searched?

Not a value, but a position: how many elements i to take from the shorter array A. The number taken from B is then fixed, j = half − i, so the two left parts always hold half of all the numbers. Only i is searched.


How do you know a cut is correct?

Both arrays are sorted, so the left parts are ≤ the right parts within each array already. Across arrays you only need A[i−1] ≤ B[j] and B[j−1] ≤ A[i]. If both hold, every left number is ≤ every right number, and the median sits at the cut.


Why search the shorter array?

It keeps j = half − i between 0 and len(B) for every i tried, so B's indexes never go out of range, and it makes the search O(log min(m, n)).

New to the technique behind this problem? Watch it run step by step:

Binary Search Visualization

Applying for software engineering roles? Free, no sign-up:

AI resume checker: match your resume to the job description