Pattern GuideStacks & Queues
Core Data Structure

Stacks & Queues

"LIFO for recent backtracking tasks, FIFO for fair chronological processing."

7 min read
Fundamental Concept
True O(1) Ops
01
CORE INTUITION

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.

02
STACKS

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.

Signals:Bracket NestingSequence ReversalBacktracking MazeMin Stack

* Need the stack to stay sorted? See Monotonic Stack.

Stack Trace Demo: Push & Pop Operations

Operation Sequence
t=0
Init
t=1
push(10)
t=2
push(20)
t=3
pop() -> 20
t=4
push(30)
t=5
pop() -> 30
t=6
pop() -> 10
let stack = []; // 1️⃣ Initialize stack
stack.push(10); // 2️⃣ Push 10 onto stack
stack.push(20); // 3️⃣ Push 20 onto stack
let val1 = stack.pop(); // 4️⃣ Pop top element (20)
stack.push(30); // 5️⃣ Push 30 onto stack
let val2 = stack.pop(); // 6️⃣ Pop top element (30)
let val3 = stack.pop(); // 7️⃣ Pop top element (10)
Active Stack Tube
[ Empty Stack ]
Initialize an empty stack array.
stack_operations.js
1
// A Stack uses an array inherently in JS
2
const stack = [];
3
4
// 1️⃣ Push element onto standard stack (LIFO)
5
stack.push(1);
6
stack.push(2);
7
8
// 2️⃣ Pop element off stack
9
const topElement = stack.pop(); // returns 2
10
11
// 3️⃣ Peek at top element safely
12
const top = stack.length > 0 ? stack[stack.length - 1] : null;
03
QUEUES

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.

Signals:BFS TraversalFair Scheduler BufferData Streams

Queue Trace Demo: Enqueue & Dequeue Operations

Operation Sequence
t=0
Init
t=1
push(10)
t=2
push(20)
t=3
shift() -> 10
t=4
push(30)
t=5
shift() -> 20
t=6
shift() -> 30
Active Queue Line
[ Empty Queue Buffer ]
let queue = []; // 1️⃣ Initialize queue
queue.push(10); // 2️⃣ Enqueue 10 to back
queue.push(20); // 3️⃣ Enqueue 20 to back
let val1 = queue.shift(); // 4️⃣ Dequeue from front (10)
queue.push(30); // 5️⃣ Enqueue 30 to back
let val2 = queue.shift(); // 6️⃣ Dequeue from front (20)
let val3 = queue.shift(); // 7️⃣ Dequeue from front (30)
Variables Monitor
dequeued val:null
dequeued list:[]
Initialize an empty queue array.
queue_operations.js
1
// Basic array Queue (O(N) dequeue due to shift)
2
const queue = [];
3
4
// 1️⃣ Enqueue element (FIFO)
5
queue.push(1);
6
queue.push(2);
7
8
// 2️⃣ Dequeue element (O(N) operation in JS!)
9
const frontObj = queue.shift();
10
11
// Tip: For O(1) dequeue in JS, utilize a custom Linked List.
04
BONUS

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.

05
PITFALLS

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.

06
COMPLEXITY

Cheat Sheet

OperationStackQueue
Push / EnqueueO(1)O(1)
Pop / DequeueO(1)O(1) with a real queue — O(N) if backed by array.shift() (see Pitfalls)
PeekO(1)O(1)
07
PRACTICE

Ready to Practice?

Valid ParenthesesEasy
Simplify PathMedium
Evaluate Reverse Polish NotationMedium

"LIFO for the recent, FIFO for the fair."