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
- Keep a deque (double-ended queue) of indexes whose values are in decreasing order.
- When a new item arrives, drop smaller items from the back: they can never be a window maximum again.
- Drop the front if it has slid out of the window.
- The front of the deque is always the maximum of the current window. O(n) overall.
Watch it run
Loading animation…