1499. Best Median Stretch

Hard7.5 points estimatedBinary SearchPrefix SumArray

A sensor reports readings in nums. For a run of consecutive readings of length L, its median is the element at sorted position floor((L + 1) / 2) (1-based), so for an even length it is the lower of the two middle values.

Return the largest median over all runs of length at least k. Binary search the answer x: map each reading to +1 if it is at least x and to -1 otherwise, then check whether some window of length at least k has a positive sum, using prefix sums with a running minimum of earlier prefixes. Target O(n log(max value)) time and O(n) extra space.

Example 1

Input:
nums = [3,1,4,1,5,9,2,6], k = 3
Output:
6
Explanation:

The run [9, 2, 6] sorts to [2, 6, 9], whose median is 6, and no run of length 3 or more does better.

Example 2

Input:
nums = [5], k = 1
Output:
5
Explanation:

The only run is [5], with median 5.

Example 3

Input:
nums = [2,2,2], k = 2
Output:
2
Explanation:

Every run has median 2.

Constraints

1 ≤ k ≤ n ≤ 105; 1 ≤ nums[i] ≤ 109

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 6,000 msC++ 1,500 msJava 3,000 msJavaScript 3,000 msTypeScript 3,000 ms

Expected complexity

Time
O(n log(max value))
Space
O(n)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…