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
Last-In, First-Out (LIFO)
A Stack is a linear data structure that restricts access to a single end: the top. Elements are pushed onto the top and popped off the top. This strict LIFO behavior makes it the go-to structure for tracking context, undo operations, or nested relationships.
Key pattern: When a problem involves backtracking, parsing nested structures (like parentheses or HTML tags), or matching historical elements in reverse order, a stack is usually the optimal choice.
* Need the stack to stay sorted? See Monotonic Stack.
Stack Trace Demo: Push & Pop Operations
Active Stack Tube
FIFO: Order & Chronological Fairness
First-In, First-Out (FIFO)
A Queue is a linear structure operating on the principle of chronological fairness: the first element added is the first one removed. Elements are enqueued at the back and dequeued from the front.
Key pattern: Essential for Breadth-First Search (BFS) level-by-level traversals, handling task scheduling, managing messaging queues, or buffering data streams in order of arrival.
Queue Trace Demo: Enqueue & Dequeue Operations
Variables Monitor
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."