22. Median of Two Sorted Arrays
hardAsked at PostmanFind the median of two sorted arrays in logarithmic time.
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
0 <= m, n <= 10001 <= m + n <= 2000-10^6 <= nums[i] <= 10^6
Examples
Example 1
nums1 = [1,3], nums2 = [2]2.0Example 2
nums1 = [1,2], nums2 = [3,4]2.5Approaches
1. Merge and pick
Merge both arrays in O(m+n) then pick the middle element(s).
- Time
- O(m+n)
- Space
- O(m+n)
const a = [...nums1, ...nums2].sort((x,y)=>x-y);
return a.length % 2 ? a[a.length>>1] : (a[a.length/2-1] + a[a.length/2]) / 2;Tradeoff:
2. Binary search on partitions
Binary search the smaller array for a partition i such that left-half of A + left-half of B has correct size and maxLeft <= minRight on both sides.
- Time
- O(log(min(m,n)))
- Space
- O(1)
function findMedian(A, B) {
if (A.length > B.length) [A, B] = [B, A];
const m = A.length, n = B.length, half = (m + n + 1) >> 1;
let lo = 0, hi = m;
while (lo <= hi) {
const i = (lo + hi) >> 1, j = half - 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:
Postman-specific tips
Postman likes the partition-search insight because it generalizes to merging sorted response pages from paginated APIs without buffering both pages.
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 Postman interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →