1505. Middle of the Middles
A river station logs n daily water levels in nums. For any list of L numbers, its median is the element at 1-based position floor(L / 2) + 1 after sorting, so an even-length list uses the upper of its two middle values.
Take every contiguous stretch of days, which gives n(n + 1) / 2 stretches, and compute the median of each one. Return the median, by the same rule, of that whole collection of medians. Duplicates are counted with multiplicity.
Hint: binary search a candidate value x over the sorted distinct levels. Mark each level +1 when it is at least x and -1 otherwise; a stretch has median at least x exactly when its marks sum to a non-negative number, and such stretches can be counted with a Fenwick tree over prefix sums or a running counter. The largest x with enough such stretches is the answer. Aim for O(n log n) time and O(n) extra space.
Example 1
- Input:
- nums = [5,1,9]
- Output:
- 5
- Explanation:
The six stretch medians are 5, 1, 9, 5, 9 and 5 (upper median for even lengths), sorted 1,5,5,5,9,9, and the element at position 4 is 5.
Example 2
- Input:
- nums = [7]
- Output:
- 7
- Explanation:
A single day gives one stretch whose median is 7.
Example 3
- Input:
- nums = [2,2,2,2]
- Output:
- 2
- Explanation:
Every stretch has median 2, so the middle of the middles is 2.
Constraints
1 ≤ n ≤ 5 * 104
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 n)
- Space
- O(n)