Quick revision
The short answer
The median of two sorted arrays is a binary search problem in which we search over a cut rather than a value. We binary search how many elements the shorter array gives to the lower half of the combined order, check the four values beside the cut, and read the median from them. It runs in O(log(min(m, n))) time and O(1) space.
The solution
What it costs
| Approach | Time | Extra space |
|---|---|---|
| Merge everything, read the middle | O(m + n) | O(m + n) |
| Merge to the middle, keep two values | O(m + n) | O(1) |
| Binary search on the cut | O(log(min(m, n))) | O(1) |
What to remember
We found the median of two sorted arrays by noticing that the lower half of all the values is a front part of a plus a front part of b, so the answer hangs on one number, how many values come from a. Binary search found that number by testing the four values beside each cut, in O(log(min(m, n))) time and O(1) space. The clue to remember is sorted input with a logarithmic time limit, which means binary search, sometimes over a count rather than a value.
1Two sorted lines of children, and the child in the middle
Picture two classes of children standing in the playground in two lines, each line already arranged from the shortest child to the tallest. The teacher wants to know which child would stand exactly in the middle if both classes formed one line by height. The obvious way is to march both lines together and count to the middle. But each line is already in order, so all she really has to decide is how many children from each line belong to the shorter half of everyone. Once she knows that, the middle child is standing right at the edge of that shorter half.
Our problem is the same with numbers. We are given two arrays, a and b, each sorted in increasing order, and we must return the median of all their values together. The median is the middle value when all the values are written in order. If the count is odd there is one middle value; if it is even, the median is the average of the two middle values, which is why the answer is a double. For a = [1, 2] and b = [3, 4], the order is 1, 2, 3, 4 and the median is (2 + 3) / 2 = 2.5.
We will keep one example for the whole article: a = [1, 3, 8, 9, 15] and b = [7, 11, 18, 19, 21, 25]. Let us do it by hand. Writing all the values in order gives 1, 3, 7, 8, 9, 11, 15, 18, 19, 21, 25. That is eleven values, so the median is the sixth, the one with five values before it and five after it, which is 11.
Now look at where the six smallest values came from. Four of them, 1, 3, 8 and 9, are the first four values of a, and two, 7 and 11, are the first two values of b. We will call these six smallest values the lower half. It took a front part of each array and nothing else. Keep that in mind, because the fast solution grows out of it, and it is why this problem is smaller than its reputation: the only real choice is one number, how many values come from a.
Top row: a. Bottom row: b. The marked cells are the six smallest values of both arrays together.
- m, n
- 5, 6
- total
- 11
- median
- 11
1The six smallest of all eleven values are 1, 3, 8, 9 from a and 7, 11 from b. The largest of those six, 11, is the median.
What to assume
- Can the arrays have different lengths?
- Yes.
- Can one be empty?
- Yes, but not both, because then there is no median, and the code throws an exception.
- Can values repeat?
- Yes.
- And how fast must it be?
- The classic version asks for
O(log(m + n))time, where m is the length of a and n the length of b.
A careful candidate asks a few questions first. Can the arrays have different lengths? Yes. Can one be empty? Yes, but not both, because then there is no median, and the code throws an exception. Can values repeat? Yes. And how fast must it be? The classic version asks for O(log(m + n)) time, where m is the length of a and n the length of b. That last answer is an important hint.
Your turn
Solve it before you read on. Above is one example with the result expected for it. Under What to assume are the points this solution takes as given. Say your approach aloud or type it below, and write the code in your own editor. Then take one hint at a time and compare.
2How to recognise that binary search fits here
When most of us first read this question, we think of merge sort, which joins two sorted arrays by repeatedly taking the smaller front value. That instinct gives the right answer, so it will be our first attempt. But the question asks for logarithmic time, and merging touches every value, so it cannot be the final answer. Let us look at what the words of the question are telling us.
The first clue is the word sorted. Sorted data lets one comparison tell us about many values at once. If we learn that 8 from a is smaller than 19 from b, we also know, without looking, that 1 and 3, which come before 8 in a, are smaller than 19 too. Sorted input is an invitation to skip work.
The second clue is the time limit. The letter O describes how the work grows with the input, and log means it grows very slowly: for a million values, about twenty steps. The only way to finish in so few steps is to throw away a large share of the possibilities at every step, usually half. Halving again and again is the signature of one technique.
That technique is binary search, which means searching by splitting in two. You know it from the game where a friend thinks of a number between 1 and 100 and answers only higher or lower: you guess 50, and whatever the answer, half the numbers are gone. The general rule is that binary search works whenever a guess can be tested with a yes or no question that tells us on which side the answer lies, and the answers flip only once as the guess grows. The guess need not be a value in an array. Here we will guess a count, how many values of a belong to the lower half, a number from 0 to m.
Some patterns look similar but do not fit. Two pointers walking through both arrays is exactly the merge, one value per step. A heap that pops the smallest values up to the middle is also linear. Gluing the arrays together and sorting them is slower still. None of them halves anything, and halving is what the time limit asks for.
3The honest first attempt, a brute force merge of the two lines
The honest first attempt, the brute force, is what the teacher would do with no cleverness at all: march both lines into one and count to the middle. It is clearly correct, and it will show us exactly which work is wasted.
We keep one finger on the front of each array, compare the two values under the fingers, copy the smaller into a new array and move that finger on. By hand: 1 against 7 gives 1, 3 against 7 gives 3, 8 against 7 gives 7, then 8, 9 and 11. That is six values, and the sixth is our median, but the merge does not know to stop, so it carries on until the new array holds all eleven. Only then do we read index 5.
The merged array of all eleven values. Only the value at index 5 is the answer.
- copied
- 11
- extra array
- 11 ints
1The merge copies all eleven values into a new array, taking the smaller front value of a or b each time.
- needed
- index 5
- median
- 11
2The median is the value at index 5, which is 11. The five values after it were copied for nothing, and of the five before it we only needed to know that they are smaller.
Read in the order it runs, the first while loop is the comparing we did by hand. When one array runs out, one of the next two loops copies whatever is left of the other. Then n % 2 tells us whether the count is odd, so the middle is all[n / 2], or even, so we average the two middle values, adding them as a long so that two large ints cannot overflow.
Now let us count. Our example copied eleven values into an array of eleven ints. For lengths m and n the merge copies m + n values, so the time grows in step with m + n, written O(m + n), and the new array takes O(m + n) extra space.
4From the merge to a binary search over the cut
The picture shows the waste plainly, since we built a whole new array to read one value. Stopping the merge at the middle saves the space, but it still walks about half the values, so it is still linear. To do better we must stop walking value by value.
A beginner often asks why we cannot simply binary search for the median value inside a. The trouble is that the median may live in either array, and whether a value is the median depends on how many values of the other array are smaller. So instead we go back to the teacher's question: how many values from each array belong to the lower half?
Here is the first observation. The lower half is always a front part of a plus a front part of b, because if 9 is in the lower half then 8, which comes before it in a, must be too. Let half = (m + n + 1) / 2 be the size of the lower half; for our example (5 + 6 + 1) / 2 = 6. If we take i values from a, we must take j = half - i from b. The place where we split the two arrays we will call the cut. So the problem shrinks to choosing one number, i, from 0 to m.
The second observation tells us how to test a guess. We name the last value we take from a aLeft. The first value of a that we leave behind is aRight, and bLeft and bRight are named the same way in b. Inside each array the order is already right, so the guess is right exactly when the two cross checks hold: aLeft <= bRight and bLeft <= aRight. In words, nothing on the left of the cut is bigger than anything on the right. The picture tries three guesses.
Marked cells are the lower half for one choice of i. The compared cells are the four values beside the cut.
- i, j
- 5, 1
- aLeft, aRight
- 15, none
- bLeft, bRight
- 7, 11
- test
- 15 > 11 fails
1Take i = 5 from a and j = 1 from b. The left side holds 15 from a, but 11 from b sits on the right, and 15 > 11. We took too many from a.
- i, j
- 2, 4
- aLeft, aRight
- 3, 8
- bLeft, bRight
- 19, 21
- test
- 19 > 8 fails
2Take i = 2 from a and j = 4 from b. Now 19 from b is on the left while 8 from a is on the right, and 19 > 8. We took too few from a.
- i, j
- 4, 2
- aLeft, aRight
- 9, 15
- bLeft, bRight
- 11, 18
- test
- both hold
3Take i = 4 from a and j = 2 from b. Both tests hold: 9 <= 18 and 11 <= 15, so every value on the left is at most every value on the right.
We keep two numbers, lo and hi, the smallest and largest counts still possible, starting at 0 and m. Now the question every beginner should ask: after a failed test, which way do we move? If aLeft > bRight, as in the first frame, the last value taken from a is too big, so the right i is smaller and we set hi = i - 1. If bLeft > aRight, as in the second, we took too few from a and set lo = i + 1. The answers flip only once, because as i grows, aLeft can only grow and bRight can only shrink. That single flip is what binary search needs.
At a cut that passes, the median sits right beside it. With an odd total the lower half has the extra value, because half rounds up, so the median is its largest value, max(aLeft, bLeft). With an even total it is the average of that and the smallest value on the right, min(aRight, bRight).
Two details are where beginners slip. When i is 0 there is no aLeft, and reading a[i - 1] would throw; when i is m there is no aRight. We fill a missing left value with Integer.MIN_VALUE and a missing right value with Integer.MAX_VALUE, so the tests always pass on that side. Using 0 or -1 instead is tempting, but it breaks arrays with negative numbers. The second detail is to search the shorter array. If we searched b here, a guess of 0 from b would ask for six values from a, which has only five.
5Watching the cut move on the example
The picture plays the binary search on our arrays, a on top and b below. The marked cells are the lower half for the current guess, and the compared cells are the four values beside the cut. Watch the range lo to hi in the panel: it starts as all six counts, 0 to 5, and every failed test throws part of it away.
Top row a, bottom row b. Marked cells are the lower half for the current guess; compared cells are the four values beside the cut.
- half
- 6
- lo, hi
- 0, 5
1We search the shorter array, a. The lower half must hold half = (5 + 6 + 1) / 2 = 6 values, and i, the count taken from a, can be 0 to 5.
- half
- 6
- lo, hi
- 0, 5
- i, j
- 2, 4
2The first guess is i = (0 + 5) / 2 = 2, so j = 6 - 2 = 4. The lower half would be 1, 3 from a and 7, 11, 18, 19 from b.
- lo, hi
- 0, 5
- i, j
- 2, 4
- aLeft, aRight
- 3, 8
- bLeft, bRight
- 19, 21
- test
- 19 > 8 fails
3We look at the four values beside the cut.
aLeft= 3 <=bRight= 21 is fine, butbLeft= 19 >aRight= 8, so a value of b on the left is too big.- half
- 6
- lo, hi
- 3, 5
- ruled out
- i = 0, 1, 2
4We took too few from a, so every i up to 2 is wrong and lo becomes i + 1 = 3. The first three values of a are now surely in the lower half.
- half
- 6
- lo, hi
- 3, 5
- i, j
- 4, 2
5The next guess is i = (3 + 5) / 2 = 4, so j = 6 - 4 = 2. The lower half would be 1, 3, 8, 9 from a and 7, 11 from b.
- lo, hi
- 3, 5
- i, j
- 4, 2
- aLeft, aRight
- 9, 15
- bLeft, bRight
- 11, 18
- test
- both hold
6Again we check the cut.
aLeft= 9 <=bRight= 18 andbLeft= 11 <=aRight= 15, so nothing on the left is bigger than anything on the right.- i, j
- 4, 2
- leftMax
- max(9, 11) = 11
- return
- 11.0
7The cut is valid and the total, 11, is odd, so the median is the largest value of the lower half,
max(9, 11)= 11. The search took two guesses.
Let us read the important frames back. In the second frame the guess is the middle of 0 to 5, which in integer division is 2, so j = 4. The third shows why it fails: 19 from b sits in the lower half while the smaller 8 from a was left out. We took too few from a, so lo jumps to 3, and half the counts are gone in one step.
In the fifth frame the guess is the middle of 3 to 5, which is 4, so j = 2. Both checks hold, 9 <= 18 and 11 <= 15. The total is odd, so the median is max(9, 11) = 11, the same value we found by writing out all eleven numbers, after two guesses instead of eleven copies.
The even case works the same way. For a = [1, 2] and b = [3, 4], half is 2. The guess i = 1 fails because bLeft = 3 > aRight = 2, so lo = 2. The guess i = 2 takes all of a and nothing from b; the missing values become the sentinels, both tests pass, and the median is (2 + 3) / 2 = 2.5.
6The complete Java program
Here is the whole program. main runs our example, an odd and an even case with small arrays, and a case where the shorter array is empty, and each comment shows what that line prints.
Let us read findMedian in the order it runs. The first line checks which array is shorter, and if a is the longer one it calls itself with the arrays swapped, so the rest of the method can trust that a is shorter. The next two lines read the lengths m and n and refuse two empty arrays with an IllegalArgumentException, because there is no median to return. Then half is computed, and lo and hi start at 0 and m, the smallest and largest count we could take from a.
Inside the loop, i is the middle of the remaining range and j = half - i follows from it. The next four lines read the values beside the cut, putting the sentinels where a value is missing, which is why the code needs no special cases for empty front parts.
Then comes the test. If both cross checks hold, we return leftMax for an odd total or the average of leftMax and rightMin, summed as a long. If aLeft > bRight we took too many from a and move hi down to i - 1; otherwise we took too few and move lo up to i + 1. The final throw is reached only for bad input, such as unsorted arrays. main prints 11.0, 2.0, 2.5 and 5.0.
7How much it costs, and the cases at the edges
Let us count on the example first. The shorter array has five values, so there were six possible counts. The first guess cut them to three, and the second found the answer. In general each round at least halves the range of i, which starts with min(m, n) + 1 choices, so the loop runs about log2(min(m, n)) times with a fixed handful of comparisons each. The time is O(log(min(m, n))), even better than the O(log(m + n)) the question asked for. The space is O(1), a few ints whatever the lengths, where the merge needed a new array of m + n values.
| Approach | Time | Extra space |
|---|---|---|
| Merge everything, read the middle | O(m + n) | O(m + n) |
| Merge to the middle, keep two values | O(m + n) | O(1) |
| Binary search on the cut | O(log(min(m, n))) | O(1) |
Now the edges. If the shorter array is empty, as in the last line of main, then lo and hi are both 0, the only guess is i = 0, and j = half takes the whole lower half from b. Both values of a are missing, the tests pass at once, and the median comes straight from b, which is why we get 5.0. Two empty arrays are the one input we refuse. Without the check at the top, every value beside the cut would be a sentinel and the method would return a meaningless number, so it throws an IllegalArgumentException instead.
Arrays of very different lengths need nothing special, because we always search the shorter one. Repeated values are fine, because the tests use <= rather than <, so equal values on both sides of the cut count as being in order. Very large values are summed in a long.
8Follow-up questions
Why is half (m + n + 1) / 2 and not (m + n) / 2?
Adding 1 before dividing makes the lower half take the extra value when the total is odd. For our eleven values half is 6, so the lower half holds six values and the median is simply its largest one. For an even total the + 1 changes nothing, because integer division throws it away: (4 + 1) / 2 is still 2. With (m + n) / 2 the code would still work, but for an odd total the median would be the smallest value on the right instead.
How would you find the k-th smallest value of the two arrays instead?
We use the same cut with half replaced by k. We binary search how many of the k smallest values come from a, with i between max(0, k - n) and min(k, m) so that j = k - i always fits in b, and at the valid cut the answer is max(aLeft, bLeft). The median is just the case where k is the middle position.
9Conclusion
We found the median of two sorted arrays by noticing that the lower half of all the values is a front part of a plus a front part of b, so the answer hangs on one number, how many values come from a. Binary search found that number by testing the four values beside each cut, in O(log(min(m, n))) time and O(1) space. The clue to remember is sorted input with a logarithmic time limit, which means binary search, sometimes over a count rather than a value.
Open with
Let me confirm the setup: both arrays are sorted ascending, they can differ in length, one may be empty but not both, and I return a double because an even total averages two values.
Then, if they want more
Merging them as in merge sort and reading the middle works, but it is O(m plus n).
The lower half of the combined order is a prefix of a plus a prefix of b, so I only choose how many values, i, come from a; then j is half minus i, where half is m plus n plus one, over two.
A choice is right when a's last left value is at most b's first right value and b's last left value is at most a's first right value. If a's left value is too big I took too many from a and move hi down; otherwise I move lo up. Missing values at the edges become Integer.MIN_VALUE and MAX_VALUE.
At the right cut, the median is the larger left value for an odd total, or its average with the smaller right value for an even total, summed as a long. I search the shorter array so j always fits, which gives O(log of the smaller length) time and O(1) space. I would test an empty array, very different lengths and duplicates.
About this answer
- Last updated
- 15 November 2026
- Written for
- Java 21, using only java.util
- Checked
- The Java solution was compiled and run, and each printed result matches the comment beside it. The pictures are checked against the format when the site is built. The explanation around the code is a study note: confirm anything critical against the documentation below. What the checks cover
- Where the question comes from
- Public interview write-ups, reworded by Scrivio; counted 17 times in that collection. How it is counted
- Official documentation
- java.util, package documentation
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "Find the median of two sorted arrays combined.": https://scrivio-interview-library.netlify.app/data-structures/solutions/find-the-median-of-two-sorted-arrays-combined-2fe9f2/