← All patterns
8 / 29
Stacks, Queues & Heaps

Queue

🎟️
Picture this

A velvet-roped line of guests in the waiting room — first to arrive is first to be seen, no cutting.

When you see it

Signal words

If the prompt uses any of these, this pattern should come to mind first.

FIFOlevel by levelfirst come first servedmoving averagerecent counter

Ask yourself

  1. Process in arrival order (FIFO)?
  2. Sliding max/min over a stream → monotonic deque.
  3. Often the engine inside BFS.

Canonical template

const q = [start];
for (let head = 0; head < q.length; head++) {
  const cur = q[head];
  for (const nxt of neighbors(cur)) q.push(nxt);
}

Common pitfalls

Using a list .pop(0) — O(n); use a deque.

Forgetting to mark visited before enqueue (dupes).