Skip to content
BytePatterns

Median Of Two Sorted Lists

HardSearching#binary-search#partitioning~50m

Problem

Two lists are each already sorted in non-decreasing order. Return the median of all their values taken together, as a decimal number: the middle value when the combined count is odd, and the average of the two middle values when it is even. At least one value exists overall, but either list on its own may be empty. Merging the lists outright is too slow; aim for a logarithmic number of steps.

Examples

Input:  a = [1, 3], b = [2]
Output: 2.0
Why:    the combined values are 1, 2, 3 and the middle one is 2
Input:  a = [1, 2], b = [3, 4]
Output: 2.5
Why:    an even count averages the two middle values
Input:  a = [], b = [1]
Output: 1.0
Why:    edge case, one list is empty and the other supplies everything

Hints

0 / 3

Stuck on the idea rather than the code? Binary Search Variants covers it.