Two-Station Median

Hardbinary searchAlso known as Median of Two Sorted Arrays

A mountain rescue team has two weather stations, one on the north ridge and one on the south ridge. Each night, each station logs temperature readings in whole degrees and keeps them sorted from coldest to warmest. The two stations do not always log the same number of readings.

The team's morning report uses the median of all readings from both stations together: the middle value, or the average of the two middle values when the total count is even. The base asks a station for one reading at a time, by position, over a slow radio link, so you want to find the median by asking for only a few readings, not by pulling in everything and merging it.

Your task

Write medianReading(north, south). Both lists are sorted in non-decreasing order. Return the median of all readings from both lists combined, as a number. If the combined count is even, return the average of the two middle values (which may end in .5).

At least one list is non-empty. Aim for O(log(min(m, n))), where m and n are the two lengths.

medianReading(north: int[], south: int[]) → float Numbers are accepted within 1e-6.

Examples

Example 1
Input
north = [-3, 1, 4]
south = [-1, 2]
Output
1
Why

All five readings in order: -3, -1, 1, 2, 4. The middle one is 1.

Example 2
Input
north = [2, 6]
south = [3, 9]
Output
4.5
Why

In order: 2, 3, 6, 9. Four readings, so average the middle two: (3 + 6) / 2 = 4.5.

Example 3
Input
north = [1, 2, 3]
south = [10, 11, 12, 13]
Output
10
Why

In order: 1, 2, 3, 10, 11, 12, 13. The middle (4th) reading is 10, from the south list. The whole north list sits below the median.

Constraints

  • 0 ≤ north.length, south.length ≤ 10,000
  • 1 ≤ north.length + south.length
  • -50 ≤ each reading ≤ 50
  • Answers within 0.000001 of the expected value are accepted.
Start with brute force

Merge the two sorted lists into one, as in merge sort, and read off the middle. That is O(m + n), and you can stop the merge halfway, but it is still linear.

Linear is fine for 20,000 readings on a fast machine. The point of this problem is the harder question: you only need to know where the middle cut falls, and that can be found with a binary search over the shorter list, about 14 peeks for 10,000 readings.

Hints

0 of 4 shown

Walkthrough and solution

Unlocks when you pass every test. Stuck for a while? Looking is fine too, as long as you then close it and write the code yourself.

Ctrl+Enter runs

Run your code to see results here. Run checks the examples. Submit checks every test, including hidden edge cases.

Write code