codejump
HardPythonJavaScriptTypeScript

Sliding Window — Maximum with a Monotonic Deque

AlgorithmsSliding WindowQueueMonotonic Queue

A window of size k slides over nums one position at a time, from the left
edge to the right edge. Return the maximum of each window, in order.

Recomputing each maximum is O(n·k). Keep instead a deque of indices whose
values are strictly decreasing from front to back. The front is always the
current maximum; a new value evicts every smaller value from the back (they
can never be a maximum again), and the front leaves once it slides out of the
window. Each index enters and leaves once: O(n).

Examples

solve([1, 3, -1, -3, 5, 3, 6, 7], 3)  → [3, 3, 5, 5, 6, 7]
solve([1], 1)                         → [1]
solve([9, 8, 7, 6], 2)                → [9, 8, 7]

Constraints

  • 1 <= k <= nums.length <= 100000
  • The result has nums.length - k + 1 values.

Sample tests

Test #1The classic example
Input: [[1,3,-1,-3,5,3,6,7],3]
Output: [3,3,5,5,6,7]
Test #2One element, window of one
Input: [[1],1]
Output: [1]
Test #3Decreasing values: the maximum slides out every time
Input: [[9,8,7,6],2]
Output: [9,8,7]