Skip to content
StackDecode
Stacks & queuesAnimated

Sliding Window Maximum

A decreasing deque keeps the maximum at its front.

Time

O(n)

Extra space

O(k)

Use it for

Window maxima in linear time.

How it works

  1. Keep a deque (double-ended queue) of indexes whose values are in decreasing order.
  2. When a new item arrives, drop smaller items from the back: they can never be a window maximum again.
  3. Drop the front if it has slid out of the window.
  4. The front of the deque is always the maximum of the current window. O(n) overall.

Watch it run

Loading animation…