Command Palette

Search for a command to run...

Module 10

Queue, Deque and Monotonic Queue

First in, first out: simulate lines, build circular buffers, and keep a window's maximum ready at the front of a monotonic deque.

Intermediate 3 lessons 5 problems ~40 min of lessons

A queue serves items in arrival order. It's the backbone of breadth-first search, task scheduling and rate limiting. A deque (double-ended queue) adds and removes at both ends, so it can act as a stack, a queue, or something cleverer.

The cleverer thing is the monotonic deque: by throwing away elements that can never be the answer, it keeps the maximum (or minimum) of a sliding window at its front, giving O(n) for problems that look like they need a heap.

Best after: Stack and Monotonic Stack, Sliding Window

Part 1

Learn the ideas

Part 2

Solve the problems

In order of difficulty. Each one shows the pattern it teaches.

  1. Simulate with a queue first, then notice the formula that skips the simulation.

  2. Amortised analysis in action: two stacks reverse order lazily, so each element moves at most twice.

  3. A queue as a sliding time window: add new events at the back, expire old ones from the front.

  4. A fixed array with a head index and a size, wrapping with modulo: the structure inside ArrayDeque and ring buffers.

  5. The monotonic deque gives each window's maximum in O(n) total, beating a heap's O(n log n).