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
- Process in arrival order (FIFO)?
- Sliding max/min over a stream → monotonic deque.
- 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).