Sliding window · Hard
A performance panel displays a median over the most recent k requests. Sorting every new window is too slow.
Return the median of every full fixed-width window.
Input
Call
- Implement
solve(input)and return its result. Do not print fromsolve.
Input object
{ values: integer[], width: integer }
Input rules
- For even width the median is the arithmetic mean of the two central values.
What each field means
values— latency measurements in arrival order.width— the number of measurements in each complete sliding window.
Output
Return value and rules
- Return one median per complete window, moving the window one position at a time.
- For odd width, use the middle sorted value. For even width, average the two middle values.
- Return
[]when the input is shorter thanwidth.
Constraints
- 0 <= values.length <= 20000; 1 <= width <= 20000
- Values are integers in [-1000,1000]. Half-integer medians are exact.
Examples
Example 1
{
"values": [
1,
4,
2,
3
],
"width": 3
}Returns
[
2,
3
]Example 2
{
"values": [
1,
4
],
"width": 2
}Returns
[
2.5
]Required complexity
O((n + 2001) log 2001) time and O(2001) space