Skip to content

Practice Median of Two Sorted Arrays

Read the task, work through the examples, and check your approach against the constraints. Use the original LeetCode task for coding and submissions.

Hard#4
LeetCode Problem

Median of Two Sorted Arrays

Problem Statement

Given two sorted arrays nums1 and nums2 of size m and n respectively, return the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)). Practice approach: Binary-search a partition of the shorter array. Choose the other array’s partition so the left side contains floor((m + n + 1) / 2) entries. A partition is valid when each left-side maximum is at most the opposite right-side minimum. Treat a missing left neighbor as negative infinity and a missing right neighbor as positive infinity. If the shorter array’s left value is too large, move its partition left; if its right value is too small, move right. For an odd total, return the larger left value; for an even total, average that value and the smaller right value. For [1, 2] and [3, 4], the valid boundary separates 2 from 3, giving 2.5. An empty input array is handled by the same boundary rules. The search takes O(log(min(m, n) + 1)) steps, with constant work for an empty shorter array, and O(1) auxiliary space.

Source: Median of Two Sorted Arrays on LeetCode. Use the original task for its coding environment and submissions.

Examples

# Example 1

Input
nums1 = [1,3], nums2 = [2]
Output
2.00000

# Example 2

Input
nums1 = [1,2], nums2 = [3,4]
Output
2.50000

Constraints

nums1.length == m
nums2.length == n
0 <= m <= 1000
0 <= n <= 1000
1 <= m + n <= 2000
-10^6 <= nums1[i], nums2[i] <= 10^6

Related LeetCode Problems

Practice more problems similar to Median of Two Sorted Arrays.

Review your practice with PhantomCodeAI

After trying the problem yourself, use the app to discuss your approach, complexity, and edge cases.