Learn / Stacks and queues

Monotonic deque

For the maximum of every window of size k, keep a deque of indexes whose values decrease from front to back. A new value removes smaller ones from the back; the front leaves when it falls out of the window. The front is always the window's maximum, and the whole scan is O(n).

How to recognise it

  • A fixed-size window slides along an array.
  • You need the maximum or minimum of every window.
  • O(n × k) is too slow.

The deque

A deque can add and remove at both ends in O(1). Store indexes, so that you can tell when one has left the window.

for i from 0 to n - 1:
    while dq and a[back] <= a[i]: pop back     # never the maximum again
    push i at the back
    if front <= i - k: pop front               # left the window
    if i >= k - 1: record a[front]

For the minimum, flip the comparison so values increase from front to back. With both deques you get the minimum and the maximum of every window in one pass.

Why O(n)

Each index is added once and removed at most once, from one end or the other.

Common mistakes

  • Storing values, so you cannot tell when the front left the window.
  • Recording an answer before the first window is complete.

Problems

0 of 2 solved

Check yourself

Why can a value be removed when a bigger one arrives after it?

Where is the maximum of the current window?

With k = 3, at i = 5 which indexes have left the window?