Order Is the Clue
The Rules of Order
Stacks and Queues aren't complex lookup arrays — they are access restrictors. They wrap a collection and force you to interact strictly with the ends.
Stack (LIFO - Last In First Out): Only touch the most recent item. Use this when a problem involves nesting, recursion, or backtracking — you need to undo, rewind, or match the newest thing first.
Queue (FIFO - First In First Out): Only touch the oldest item. Use this when a problem involves chronological scheduling, fairness, or level-by-level BFS expansion — you process things in the exact order they arrived.
LIFO: Backtracking & Nesting
Every element is placed on the top of the stack. You can only remove from the top. This gives you access to only the most recent item.
Stack Trace Demo: Valid Parentheses Check on {[()]}
Active Stack Tube
Strategy Blueprint
When the stack itself must stay sorted at all times (not just LIFO order) — see Monotonic Stack.
FIFO: Order & Chronological Fairness
New elements enter at the back (enqueue), and processed elements leave from the front (dequeue). This guarantees first-come, first-served chronological scheduling.
Queue Trace Demo: Process Tasks chronological queue
Variables Monitor
Strategy Blueprint
Deque: Both Ends
When One End Isn't Enough
A Deque (double-ended queue) allows O(1) insert and remove at both ends. It combines stack and queue access into one structure. The most common algorithmic use is maintaining a monotonic deque for sliding window maximum/minimum problems.
Key pattern: As the window slides, remove expired indices from the front and pop smaller values from the back. The front of the deque always holds the current window's maximum. See the Sliding Window guide for details.
Common Mistakes
Underflow Errors
Attempting to pop or peek on an empty Stack/Queue. Always check !isEmpty() before retrieving values to avoid index out of bounds crashes.
Shift Complexity
Using array.shift() in JavaScript is O(N) due to index re-allocations. For true O(1) queues, use a Linked List or a specialized Deque implementation.
Cheat Sheet
| Operation | Stack | Queue |
|---|---|---|
| Push / Enqueue | O(1) | O(1) |
| Pop / Dequeue | O(1) | O(1) with a real queue — O(N) if backed by array.shift() (see Pitfalls) |
| Peek | O(1) | O(1) |
Ready to Practice?
"LIFO for the recent, FIFO for the fair."