Finding the Median of Two Sorted Arrays with JavaScript

Finding a median is easy once all the values sit in one sorted array. The interesting part of LeetCode's challenge is avoiding that work. I'll start with my straightforward combine‑and‑sort solution, then build a binary search that finds the middle without creating a merged array.
Problem Description
In LeetCode 4, Median of Two Sorted Arrays, both inputs are already sorted. We need the middle value, or the average of the middle pair, and the problem asks for O(log(m + n)) time. That last condition is what makes sorting everything again insufficient.
Here are the two shapes of answer we need to handle:
// Input:
nums1 = [1, 3];
nums2 = [2];
// Output: 2.0
// Input:
nums1 = [1, 2];
nums2 = [3, 4];
// Output: 2.5
// (Because there are an equal number of numbers, so we add the middle two: (2 + 3) / 2 = 2.5)A Simple Baseline: Combine, Sort, and Read the Middle
I like starting with the direct version because there is very little to keep in our heads. Copy both inputs into a new array, sort numerically, and read the middle. An odd length has one middle element; an even length has two, so we average them.
const findMedianSortedArrays = (nums1: number[], nums2: number[]): number => {
const merged = [...nums1, ...nums2].sort((a, b) => a - b);
const mid = Math.floor(merged.length / 2);
if (merged.length % 2 === 0) {
return (merged[mid - 1] + merged[mid]) / 2;
}
return merged[mid];
};The spread syntax creates a new array, so sorting it leaves both inputs alone. For N = m + n, the usual comparison‑sort analysis is O(N log N) time, with at least O(N) extra storage for the copy. JavaScript does not specify a universal complexity guarantee for sort, but this implementation plainly does more work than a logarithmic search.
A two‑pointer merge would make better use of the sorted inputs and take O(m + n) time. That is a useful intermediate improvement, although it still misses the requested logarithmic bound. To go further, we need to find the middle without visiting every value.
Find the Cut, Rather than Build the Combined Array
Imagine cutting each array into a left part and a right part. Together, the left parts should contain half the values, with one extra value on the left when the total is odd. We do not actually slice either array. A cut is just a count of how many values we take from it.
For a total length of seven, the combined left side needs four values. If we take one from the first array, we must take three from the second. Once we choose one cut, the other is fixed. That leaves only one position to search.
Each array is already sorted, so its own left values cannot exceed its own right values. We only need to check the two comparisons across arrays: the last value on the smaller array's left must be no greater than the first value on the larger array's right, and vice versa. When both comparisons hold, every left value belongs before every right value.
Why Search the Smaller Array?
A length of k gives us k + 1 possible cuts, including taking none or all of its values. Searching the smaller array keeps that range short. It also keeps the matching cut in the larger array within bounds: the required left‑side size is at least the smaller length and no greater than the larger length.
If smallLeft > largeRight, we have taken too many values from the smaller array. Move its cut left. Moving right could only increase smallLeft and decrease largeRight, making the mismatch worse. If largeLeft > smallRight, we have taken too few, so move right instead. Each decision discards half the remaining cut positions.
A Worked Partition
Take [1, 3, 8] and [2, 7, 10, 11]. Their total length is seven, so the left side needs four values. Start halfway through the three‑element array, with smallCut = 1 and largeCut = 3.
- The smaller array is divided as
[1] | [3, 8]. - The larger array is divided as
[2, 7, 10] | [11]. - The left boundary
10exceeds the right boundary3. We need more of the smaller array on the left, so we move its cut right.
The next cuts are smallCut = 2 and largeCut = 2. Now the parts are [1, 3] | [8] and [2, 7] | [10, 11]. The cross‑checks are 3 <= 10 and 7 <= 8, so the partition is valid. There are four values on the left, and its largest value, 7, is the median.
We have found the answer without sorting or copying the seven values. The left parts do not even need to be merged into order: their two final values tell us which one is largest.
The Binary‑Partition Implementation
This is an alternative implementation of findMedianSortedArrays; use it in place of the baseline above. The smaller and larger variables refer to the original arrays. Nothing is copied, sorted, or written back.
const findMedianSortedArrays = (nums1: number[], nums2: number[]): number => {
const smaller = nums1.length <= nums2.length ? nums1 : nums2;
const larger = nums1.length <= nums2.length ? nums2 : nums1;
const totalLength = smaller.length + larger.length;
if (totalLength === 0) {
throw new RangeError('At least one array must contain a value.');
}
const leftSize = Math.floor((totalLength + 1) / 2);
let low = 0;
let high = smaller.length;
while (low <= high) {
const smallCut = Math.floor((low + high) / 2);
const largeCut = leftSize - smallCut;
const smallLeft = smallCut === 0 ? -Infinity : smaller[smallCut - 1];
const smallRight = smallCut === smaller.length ? Infinity : smaller[smallCut];
const largeLeft = largeCut === 0 ? -Infinity : larger[largeCut - 1];
const largeRight = largeCut === larger.length ? Infinity : larger[largeCut];
if (smallLeft <= largeRight && largeLeft <= smallRight) {
const leftMaximum = Math.max(smallLeft, largeLeft);
if (totalLength % 2 !== 0) {
return leftMaximum;
}
return (leftMaximum + Math.min(smallRight, largeRight)) / 2;
}
if (smallLeft > largeRight) {
high = smallCut - 1;
} else {
low = smallCut + 1;
}
}
throw new Error('No valid partition found.');
};Empty Sides, Duplicate Values, and the Middle Pair
A cut can sit before the first element or after the last. I use -Infinity for a missing left value and Infinity for a missing right value. These sentinels make an empty side harmless in the comparisons. They are local values, not extra elements inserted into the arrays.
For [] and [2, 4], the smaller cut can only be zero. The larger cut is one, so the real boundaries are 2 and 4. The sentinels stay out of the result, and the median is 3. With a valid non‑empty combined input, the boundaries needed for the answer always include real values.
For an odd total, the left side has the extra element, so its largest value is the answer. For an even total, average the largest left value and the smallest right value. With [1, 2] and [3, 4], a valid partition puts [1, 2] on the left and [3, 4] on the right, giving (2 + 3) / 2 = 2.5.
Equal values are allowed. The checks use <=, not <, so [1, 1] and [1, 1] can have a perfectly valid partition. Negative values need no special treatment either; the comparisons work in exactly the same way.
Input Assumptions and Cost
LeetCode supplies sorted integer arrays of at most 1,000 elements each, with at least one value overall and values between -1000000 and 1000000. The final addition and division are safe within those bounds. The explicit empty‑input check rejects two empty arrays, but this function is not a validator for unsorted inputs or arbitrary JavaScript values. Checking every element first would itself take linear time.
For a non‑empty smaller array, searching its cut positions takes O(log(min(m, n) + 1)) time. When one array is empty, there is just one cut to check, so that case takes O(1) time. Written to include that constant case explicitly, the bound is O(1 + log(min(m, n) + 1)). Extra space is O(1): a fixed number of references, indices, and boundary values, with no recursion or merged array.
Edge Cases Worth Testing
I would test both orders of the inputs, especially when one is empty or much shorter. Include duplicate values, all‑negative values, and both odd and even totals. The worked examples above give us expected medians of 7, 3, 2.5, and 1; those are useful checks before trying larger inputs.
For a stronger check, generate small sorted arrays and compare the result with a simple linear merge followed by reading the median. That reference takes a different route to the answer, which makes it useful for catching a wrong cut or search direction. Also check that both input arrays are unchanged. Passing examples help catch mistakes; they do not replace the partition argument.
The Wrap‑up
The baseline is still a clear way to calculate a median when sorting a small copy is acceptable. The partition version earns its extra bookkeeping by using the order we already have. It searches only the smaller input and meets the problem's logarithmic requirement.
The part I would remember is the pair of conditions: enough values on the left, and no left value greater than a right value. Once those hold, finding the median is just reading the values beside the cuts.
Postscript
November 2026: I've added the complete binary‑partition solution and a worked trace, so you can follow how the cuts move and compare it with my original sorting example.