808. Peak latency dashboard: rolling window maximum in O(n)
Why it matters Streaming monitors for latency, loss spikes and GPU memory peaks compute rolling maxima over long windows.
Your monitoring dashboard shows the peak latency over the last w requests, updated after every request. Recomputing max() over each window costs O(n * w), which is too slow for a day of traffic. A monotonic deque does it in O(n): each index enters and leaves the deque once.
Write window_max(x, w).
- x is a list (or NumPy array) of numbers in arrival order. Values can be negative and can repeat.
- w >= 1 is the window size.
Return a list whose entry for each i from w - 1 to len(x) - 1 is max(x[i - w + 1], ..., x[i]), the max of the w most recent values. The output has len(x) - w + 1 entries. If len(x) < w, return [].
Constraints: len(x) <= 200,000 and w <= len(x) in the large tests, so an O(n * w) loop will hit the time limit. Note that the oldest value must leave the window exactly when the window moves past it: a big value from w + 1 requests ago no longer counts.
def window_max(x, w)Example 1
Input: (latency in ms, w = 3): window_max([120, 95, 310, 140, 130, 125, 500, 90, 88, 101], 3)
Output: [310, 310, 310, 140, 500, 500, 500, 101]
Explanation: The 310 ms spike shows for exactly three windows, then drops out.
Example 2
Input: window_max([1, 3, -1, -3, 5, 3, 6, 7], 3)
Output: [3, 3, 5, 5, 6, 7]
Example 3
Input: x = [4, 2], w = 1
Output: [4, 2]
Constraints
- Python 3 standard library. Code runs in your browser.
- Your code must pass all 13 tests to be accepted.
Hint 1
Store indices, not values, so you can tell when the front leaves the window.
Hint 2
Before pushing i, pop back entries whose values are <= x[i].
Hint 3
The front of the deque is the answer once i >= w - 1.
Common mistakes
- Calling max(
x[i-w+1:i+1]) for every i, which is too slow for 200,000 points and a window of 1000. - Forgetting to drop the front index when it falls out of the window.
Understand the idea
Keep indices in a deque whose values decrease from front to back. A new value pops every smaller value from the back, because those can never be a window max again. The front is the current max; drop it once it leaves the window.
x = [1, 3, -1, -3, 5, 3, 6, 7], w = 3 gives [3, 3, 5, 5, 6, 7].
pop smaller from the back, push i, drop the front if it is out of range, read the front