23. Median of Two Sorted Arrays
hardAsked at CourseraFind the median of two sorted arrays in O(log(m+n)) time, a binary search hard problem Coursera uses to test candidates' ability to reason about partitioning for analytics pipelines.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
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)).
Constraints
nums1.length == mnums2.length == n0 <= m, n <= 1000-10^6 <= nums1[i], nums2[i] <= 10^6
Examples
Example 1
nums1 = [1,3], nums2 = [2]2.00000Example 2
nums1 = [1,2], nums2 = [3,4]2.50000Approaches
1. Merge and find median (O(m+n))
Merge both arrays into a sorted array, then take the middle element(s) — fails the O(log) requirement.
- Time
- O(m+n)
- Space
- O(m+n)
function findMedianSortedArrays(nums1, nums2) {
const merged = [...nums1, ...nums2].sort((a,b) => a-b);
const mid = Math.floor(merged.length / 2);
return merged.length % 2 ? merged[mid] : (merged[mid-1]+merged[mid])/2;
}Tradeoff:
2. Binary search on partition
Binary search on the smaller array to find the correct partition point such that all left-half elements are <= all right-half elements in both arrays combined. Compute median from the four boundary values.
- Time
- O(log(min(m,n)))
- Space
- O(1)
function findMedianSortedArrays(nums1, nums2) {
if (nums1.length > nums2.length) return findMedianSortedArrays(nums2, nums1);
const m = nums1.length, n = nums2.length;
let lo = 0, hi = m;
while (lo <= hi) {
const i = Math.floor((lo + hi) / 2);
const j = Math.floor((m + n + 1) / 2) - i;
const maxL1 = i === 0 ? -Infinity : nums1[i-1];
const minR1 = i === m ? Infinity : nums1[i];
const maxL2 = j === 0 ? -Infinity : nums2[j-1];
const minR2 = j === n ? Infinity : nums2[j];
if (maxL1 <= minR2 && maxL2 <= minR1) {
const maxL = Math.max(maxL1, maxL2);
const minR = Math.min(minR1, minR2);
return (m + n) % 2 ? maxL : (maxL + minR) / 2;
} else if (maxL1 > minR2) { hi = i - 1; }
else { lo = i + 1; }
}
}Tradeoff:
Coursera-specific tips
Coursera interviews emphasize algorithms for educational platforms, content recommendation systems, and scalable delivery pipelines. Medium-difficulty graph and DP problems are typical.
Solve it now
Free. No sign-up. Python and JavaScript run instantly in your browser.
Practice these live with InterviewChamp.AI
Drill Median of Two Sorted Arrays and other Coursera interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →