Stacks & Queues
LIFO, FIFO, monotonic deque and design questions.
6 pages
- Pattern 21: Stacks & Queues (incl. Monotonic Deque, Design & Simulation)Pattern guide
One-line trigger: "Process in LIFO order (stack), FIFO order (queue), or maintain a running answer over a sliding window (deque)."
- LC 20Valid Parentheses (LC 20)Easy
The most recently opened bracket must be the first one closed — that is LIFO, so a stack does the matching for free.
- LC 232Implement Queue using Stacks (LC 232)Easy
Reversing a stack into a second stack turns LIFO into FIFO. Only refill when the output stack is empty — that is what makes it amortised O(1) instead of O(n).
- LC 239Sliding Window Maximum (LC 239)Hard
An element that is smaller than a later element can never be the window max again — evict it immediately. What survives is a decreasing deque of indices…
- LC 994Rotting Oranges (LC 994)Medium
Everything rots simultaneously, so seed the queue with all rotten cells before the loop starts. BFS levels then equal elapsed minutes.
- LC 622Design Circular Queue (LC 622)Medium
Wrap indices with % capacity to reuse freed slots. Track an explicit count so "full" and "empty" are never ambiguous.