You get two lists of whole numbers, nums1 and nums2, each already sorted from smallest to largest. Either list may be empty, but not both.
Picture all the numbers from both lists in one sorted row and return its median: the middle number when the count is odd, or the average of the two middle numbers when it is even.
The target is O(log(m + n)) time, where m and n are the two lengths.
Example 1
Input: nums1 = [1, 4, 7], nums2 = [2, 3] Output: 3.0 Why: together they are 1, 2, 3, 4, 7; the middle one is 3
2 more examples and the constraints
Example 2
Input: nums1 = [1, 5], nums2 = [2, 6] Output: 3.5 Why: 1, 2, 5, 6 has two middles, 2 and 5; their average is 3.5
Example 3
Input: nums1 = [], nums2 = [4] Output: 4.0 Why: only one number, so it is the median
Constraints
- 0 ≤ m, n ≤ 1,000 and 1 ≤ m + n ≤ 2,000
- Every number is between −1,000,000 and 1,000,000
- Answers within 0.000001 of the true median are accepted
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Merge, then pick the middleO(m + n)
- Binary search the cutO(log(min(m, n)))
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 1,000 + 1,000 numbers | Verdict |
|---|---|---|---|
| Merge, then pick the middle | O(m + n) | Correct; misses the log target | |
| Binary search the cut | O(log(min(m, n))) | Best; meets the target |
m, n = the lengths of nums1 and nums2.
Edge cases to test
- One list empty. nums1 = [], nums2 = [4] gives 4.0; the cut in the empty list is always at 0.
- No overlap. [10, 20, 30] and [1, 2, 3]: one list sits wholly left of the other, so the cut lands at an end.
- Even total. Average the two middle values; [1, 5] and [2, 6] give 3.5, not 3.
- Negative numbers. [-5, -3, -1] and [-2] give −2.5; watch integer division rounding.
- Repeated values. [1, 1, 1] and [1, 1]: equal values on both sides of the cut are fine, since the checks use ≤.
Common mistakes
- Searching the longer list, so j goes negative or past the end of the other list.
- Using integer division for the even case and returning 3 instead of 3.5.
- Forgetting the −∞ and +∞ stand-ins, so an empty side crashes or blocks the right cut.
How to talk through it
- 1Clarify. Can a list be empty? Is the answer a decimal? Is O(log(m + n)) required, or is linear fine?
- 2Give the merge. Merge like merge sort and take the middle: O(m + n). Say it misses the target.
- 3Reframe as a cut. The median splits everything into two halves. Choosing how many come from the shorter list fixes the rest.
- 4Code the binary search. Explain the two cross checks and which way each failure moves the search.
- 5Test out loud. Run an empty list, an even total and two lists that do not overlap before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?