24. Median of Two Sorted Arrays
hardAsked at KlarnaFind 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, return the median of the two sorted arrays. The overall run time complexity must be O(log(m+n)).
Constraints
0 <= m, n <= 10001 <= m + n <= 2000-10^6 <= nums1[i], nums2[i] <= 10^6
Examples
Example 1
nums1 = [1,3], nums2 = [2]2.0Example 2
nums1 = [1,2], nums2 = [3,4]2.5Approaches
1. Merge then index
Merge both arrays into one sorted array, then index into the middle.
- Time
- O(m+n)
- Space
- O(m+n)
function findMedianSortedArrays(a, b) {
const m = [];
let i = 0, j = 0;
while (i < a.length && j < b.length) m.push(a[i] <= b[j] ? a[i++] : b[j++]);
while (i < a.length) m.push(a[i++]);
while (j < b.length) m.push(b[j++]);
const k = m.length;
return k % 2 ? m[(k-1)/2] : (m[k/2 - 1] + m[k/2]) / 2;
}Tradeoff:
2. Binary search partition
Binary search the partition index on the shorter array so that every element on the left side of both arrays is <= every element on the right. The median falls right at that partition.
- 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, half = Math.floor((m + n + 1) / 2);
let lo = 0, hi = m;
while (lo <= hi) {
const i = (lo + hi) >> 1;
const 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:
Klarna-specific tips
Klarna's BNPL credit-scoring team uses this O(log n) partition trick when finding percentile thresholds across two pre-sorted risk-feature streams; they grade the +Infinity/-Infinity sentinel handling more than the macro idea.
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 Klarna interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →