← Questions
Median of two sorted arrays
0
I was asked this
No reports yet. Sign in to say where you were asked it.
A coding interview question asked in Meta's technical phone screen, last asked Aug 2025. It tests binary-search and arrays.
Given two sorted arrays, return the median of all their values taken together, without merging them in full.
Interface
Unless you agree on a different interface with the interviewer, assume:
-
find_median_sorted_arrays(a: list[int], b: list[int]) -> float— withN = len(a) + len(b), the middle value whenNis odd, and the mean of the two middle values whenNis even. Always a float.
Example
find_median_sorted_arrays([1, 3], [2]) -> 2.0
find_median_sorted_arrays([1, 2], [3, 4]) -> 2.5 # (2 + 3) / 2
find_median_sorted_arrays([], [5]) -> 5.0
find_median_sorted_arrays([1, 1], [1, 2]) -> 1.0
Constraints
-
0 <= len(a), len(b) <= 1000,len(a) + len(b) >= 1. Values from-10^6to10^6. - Target O(log(min(m, n))) time.
Clarifying questions
- Can one array be empty?
- For an even total, is the answer the mean of the two middle values?
- Are there duplicates, and do they count?
What a strong answer covers
- The baseline first: a merge that stops at the middle, O(m + n) time and O(1) space.
- Binary search on how many elements the shorter array puts on the left side. The longer array's split follows, so the left side holds half of all elements.
- The partition is right when
maxLeftA <= minRightBandmaxLeftB <= minRightA, with-infand+infat the edges of the arrays. - The odd and even cases read from the four boundary values. O(log(min(m, n))) time, O(1) space.
- Tests: one array empty, all values of one array smaller, equal values, arrays of length 1.
Follow-ups
- Return the
k-th smallest value of the two arrays for anyk. - Many sorted arrays instead of two.
- The arrays are on different machines and can only answer "how many of your values are
<= x?".
Where it's asked
- Meta · Technical phone screen · Last asked Aug 202545 min · Two coding problems in CoderPad, about 20 minutes each · Usually no AI; some newer screens are AI-assisted
What it tests
No official answer yet. Write yours on the right and run it.
Nothing published yet.
Sign in to submit your code; every attempt is kept here.
Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding
