The median of a collection of numbers is its middle value once they are sorted — the point that splits the data into a smaller half and a larger half, or the average of the two middle values when the count is even. Here you are given two arrays that are each already sorted in ascending order, and you return the median of all of their values combined. This is the well-known "Median of Two Sorted Arrays" interview problem (LeetCode 4); the catch is the target running time. See median for background.
medianOfTwoSorted(a, b) // a and b each sorted ascending -> number (may be a .5)
medianOfTwoSorted([1, 3], [2]); // 2 (combined [1, 2, 3] -> middle value)
medianOfTwoSorted([1, 2], [3, 4]); // 2.5 (combined [1, 2, 3, 4] -> average of 2 and 3)
medianOfTwoSorted([], [1, 2, 3, 4]); // 2.5 (one array may be empty)
a and b are each in ascending order. You never sort them yourself..5 (a non-integer). An odd total returns the single middle value.O(log(min(m, n))) time, not the O(m + n) you get from merging the two arrays and indexing the middle.Unlock the solution & editor
Runnable editor + tests
Solve in the browser with instant Jest feedback.
Detailed solutions
Walkthroughs, edge cases, and complexity notes.
Multi-framework variants
React, Vue, Vanilla, Angular — same question, different stacks.