Two-Station Median

Hardbinary searchAlso known as Median of Two Sorted Arrays

A mountain rescue team has weather stations on the north and south ridges. Each night, each station logs temperatures in whole degrees, sorted coldest to warmest. The two counts can differ.

The morning report needs the median of both stations' readings combined: the middle value, or the average of the two middle values when the total is even. The base fetches one reading at a time over a slow radio link, so you want the median from only a few readings, not a full merge.

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

Sorted together, the five readings are -3, -1, 1, 2, 4, and the middle one is 1.

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

Sorted together, the four readings are 2, 3, 6, 9. The count is even, so the median is the average of the middle two, (3 + 6) / 2 = 4.5.

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

Sorted together, the seven readings are 1, 2, 3, 10, 11, 12, 13. The middle (4th) reading is 10, which comes from the south list, and 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, as in merge sort, and read off the middle. You can stop halfway, but it is still O(m + n).

Linear is fine for 20,000 readings, but you only need to know where the middle cut falls. A binary search over the shorter list finds it in 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