- Interview Questions
- /
- Problems
- /
- Median of Two Sorted Arrays
Median of Two Sorted Arrays
Find the median of two sorted arrays combined, in logarithmic time. A hard binary search where you search over where to cut the arrays, not over values. Solve it below in Python or JavaScript, then read the walkthrough.
Problem
You're given two arrays nums1 and nums2, each sorted in non-decreasing order. Return the median of all their elements taken together.
If the combined length is odd, the median is the middle element of the merged order. If it's even, the median is the average of the two middle elements, which may not be a whole number.
Aim for O(log(m + n)) time, where m and n are the two lengths. Answers within 10⁻⁵ of the exact median are accepted.
Example 1
- Input
- nums1 = [1, 4, 9], nums2 = [2, 6]
- Output
- 4
Merged, the values are [1, 2, 4, 6, 9]. The middle one is 4.
Example 2
- Input
- nums1 = [3, 8], nums2 = [5, 10]
- Output
- 6.5
Merged: [3, 5, 8, 10]. The middle two are 5 and 8, and their average is 6.5.
Example 3
- Input
- nums1 = [], nums2 = [7]
- Output
- 7
One array can be empty.
Constraints
- 0 ≤ nums1.length, nums2.length ≤ 10⁴
- 1 ≤ nums1.length + nums2.length
- -10⁶ ≤ nums1[i], nums2[i] ≤ 10⁶
Practice
Runs 13 tests in your browser. Python loads on the first run (about 6 MB, then cached). Press ⌘/Ctrl + Enter to run.
Get asked Median of Two Sorted Arrays in a real interview?
Interview Solver gives you a working solution live, during your actual coding interview. Invisible to screensharing.
How to solve Median of Two Sorted Arrays
Pattern: Binary search on a partition
The median splits the combined values into a left half and a right half of equal size (the left gets the extra one when the total is odd), with everything on the left ≤ everything on the right.
Picture that split as a cut through each array: take the first i elements of nums1 and the first j elements of nums2 as the left half. Since the left half has a fixed size, half = (m + n + 1) // 2, choosing i forces j = half - i. So there is really only one number to search for.
A cut is correct when nums1[i-1] ≤ nums2[j] and nums2[j-1] ≤ nums1[i]. If nums1[i-1] is too big, i is too far right; if nums2[j-1] is too big, i is too far left. That one-directional feedback is what makes binary search work. Search over the shorter array so j never goes out of range, and treat missing neighbors past either end as -∞ or +∞.
Approach 1: Merge, then pick the middle
Run the standard two-pointer merge into a new array and read off the middle element or the average of the middle two. Simple and correct, but linear in both time and space.
Time O(m + n) · Space O(m + n)
Approach 2: Walk to the middle without storing
Run the same merge but only count steps, remembering the last two values seen, and stop at position (m + n) / 2. Saves the memory but is still linear time.
Time O(m + n) · Space O(1)
Approach 3: Binary search on the cut in the shorter array
Make nums1 the shorter array. Search i over [0, m]:
i = (lo + hi) // 2,j = half - i.- Let
L1 = nums1[i-1],R1 = nums1[i],L2 = nums2[j-1],R2 = nums2[j], using-∞/+∞past the ends. - If
L1 > R2, move left:hi = i - 1. IfL2 > R1, move right:lo = i + 1. - Otherwise the cut is valid. If the total is odd, the median is
max(L1, L2). If even, it's(max(L1, L2) + min(R1, R2)) / 2.
Time O(log min(m, n)) · Space O(1)
| Approach | Time | Space |
|---|---|---|
| Merge, then pick the middle | O(m + n) | O(m + n) |
| Walk to the middle without storing | O(m + n) | O(1) |
| Binary search on the cut in the shorter array | O(log min(m, n)) | O(1) |
Solution code
Try the practice editor first. Both solutions pass every test above.
Median of Two Sorted Arrays solution in Python
def find_median_sorted_arrays(nums1: list[int], nums2: list[int]) -> float:
if len(nums1) > len(nums2):
nums1, nums2 = nums2, nums1
m, n = len(nums1), len(nums2)
half = (m + n + 1) // 2
lo, hi = 0, m
while lo <= hi:
i = (lo + hi) // 2
j = half - i
left1 = nums1[i - 1] if i > 0 else float("-inf")
right1 = nums1[i] if i < m else float("inf")
left2 = nums2[j - 1] if j > 0 else float("-inf")
right2 = nums2[j] if j < n else float("inf")
if left1 > right2:
hi = i - 1
elif left2 > right1:
lo = i + 1
else:
if (m + n) % 2:
return float(max(left1, left2))
return (max(left1, left2) + min(right1, right2)) / 2
return 0.0Median of Two Sorted Arrays solution in JavaScript
function findMedianSortedArrays(nums1, nums2) {
if (nums1.length > nums2.length) [nums1, nums2] = [nums2, nums1];
const m = nums1.length;
const n = nums2.length;
const half = Math.floor((m + n + 1) / 2);
let lo = 0;
let hi = m;
while (lo <= hi) {
const i = Math.floor((lo + hi) / 2);
const j = half - i;
const left1 = i > 0 ? nums1[i - 1] : -Infinity;
const right1 = i < m ? nums1[i] : Infinity;
const left2 = j > 0 ? nums2[j - 1] : -Infinity;
const right2 = j < n ? nums2[j] : Infinity;
if (left1 > right2) {
hi = i - 1;
} else if (left2 > right1) {
lo = i + 1;
} else {
if ((m + n) % 2) return Math.max(left1, left2);
return (Math.max(left1, left2) + Math.min(right1, right2)) / 2;
}
}
return 0;
}Common mistakes
- Binary searching over the longer array, which can make j negative or larger than the other array’s length.
- Index errors at the edges when i or j is 0 or the full length. Sentinel values of -∞ and +∞ handle all four edges uniformly.
- Integer division in the even case. Using // in Python, or integer types in a typed language, drops the .5 from answers like 6.5.
- Getting the left-half size wrong for odd totals. With half = (m + n + 1) // 2 the extra element lands on the left, so the odd-case median is max(L1, L2).
What interviewers look for
Start with the O(m + n) merge and say it's correct but doesn't meet the log bound. Then reframe: "the median is a cut that splits everything into two equal halves, and fixing the cut in one array fixes it in the other." Interviewers want to hear that reframing, because it's what turns a two-array problem into a one-variable binary search.
Write the four boundary values with sentinels before writing the search, and trace one odd and one even example, plus a case where one array is empty. Most failed attempts break on those edges, not on the main idea.
Follow-up questions
How would you find the k-th smallest element of the two arrays instead of the median?
Use the same partition search with a left side of size k instead of half, restricting i to max(0, k - n) through min(k, m). The answer is max(L1, L2). An alternative is to discard k/2 elements from one array per step for O(log k).
What if there are k sorted arrays?
Binary search on the answer value instead: for a candidate value, count elements ≤ it across all arrays with one binary search each, and narrow until the count crosses the middle position. That takes O(k log n · log(value range)).
What if the numbers arrive as a stream and you need the running median?
Keep a max-heap for the lower half and a min-heap for the upper half, rebalancing so their sizes differ by at most one. Each insertion is O(log n), and the median is read from the heap tops in O(1).
Companies that ask Median of Two Sorted Arrays
Median of Two Sorted Arrays is tagged by 127 companies in our interview dataset. The score shows how often it comes up at each company.
- Angi100%
- Anaplan100%
- Astera Labs100%
- Lockheed Martin100%
- Rippling100%
- Thryv100%
- Zenefits100%
- Fedex100%
- Offerup97%
- Yahoo96.9%
- Infor95%
- Segment94%
- Dropbox92.1%
- Bandcamp89%
- Biomérieux88%
- Proofpoint87%
- Adobe86.8%
- Red Hat86%
- Analog Devices85%
- Billcom84%
- Goldman Sachs80.1%
- Nubank79%
- Ciklum79%
- Broadcom79%
and 103 more.
Practice next
Get live help in the real interview
Working solutions in real time during your actual interview. Invisible to screensharing.
Start Free TrialNo credit card required