95. Median of Two Sorted Arrays
hardAsked at OlaFind the median of two sorted arrays in O(log(min(m,n))).
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 <= 10001 <= m + n <= 2000
Examples
Example 1
nums1 = [1,3], nums2 = [2]2.0Example 2
nums1 = [1,2], nums2 = [3,4]2.5Approaches
1. Merge then pick mid
Merge the two arrays and return the middle.
- Time
- O(m+n)
- Space
- O(m+n)
const m = [...nums1, ...nums2].sort((a,b)=>a-b); const mid = Math.floor(m.length/2);
return m.length % 2 ? m[mid] : (m[mid] + m[mid-1]) / 2;Tradeoff:
2. Binary search on shorter array
Binary search the partition of the smaller array such that left halves combined contain (m+n+1)/2 elements; verify left-max <= right-min.
- Time
- O(log min(m,n))
- Space
- O(1)
function findMedianSortedArrays(a, b) {
if (a.length > b.length) [a, b] = [b, a];
const m = a.length, n = b.length;
let lo = 0, hi = m;
while (lo <= hi) {
const i = (lo + hi) >> 1;
const j = ((m + n + 1) >> 1) - i;
const aL = i === 0 ? -Infinity : a[i-1];
const aR = i === m ? Infinity : a[i];
const bL = j === 0 ? -Infinity : b[j-1];
const bR = j === n ? Infinity : b[j];
if (aL <= bR && bL <= aR) {
if ((m + n) % 2) return Math.max(aL, bL);
return (Math.max(aL, bL) + Math.min(aR, bR)) / 2;
} else if (aL > bR) hi = i - 1;
else lo = i + 1;
}
}Tradeoff:
Ola-specific tips
Ola asks this rarely but uses it for senior IC screens; tie the partition trick to merging two sorted ETA buffers from different region brokers.
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 Ola interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →