DSA Guide
Stacks & Queues

Stacks & Queues

Last-in-first-out and first-in-first-out — and how to recognise which one a problem needs

Stacks and queues are the same idea — a sequence you add to and remove from — differing only in which end you remove from. That single choice determines which problems they solve.

Stack — Last In, First Out

Reach for a stack whenever the most recent thing is the first thing you need to resolve.

Signals that a stack is the answer

Queue — First In, First Out

Reach for a queue when things must be processed in arrival order.

Do not use a plain list as a queue

Python: list.pop(0) is O(n) because everything shifts left. Use collections.deque, whose popleft is O(1).

TypeScript: Array.prototype.shift() has the same cost. Either keep a read index into the array, or build a fresh array per BFS level.

Getting this wrong silently turns an O(n) traversal into O(n²).

Augmented Stacks

A stack can carry extra state alongside its values, giving O(1) answers to questions that would otherwise need a scan.

  • Min Stack — every entry stores the minimum as of its push

The same idea powers monotonic stacks, which keep their contents sorted and solve "next greater element" style problems in linear time.

Language Notes

OperationPythonTypeScript
Pushstack.append(x)stack.push(x)
Popstack.pop() — raises on emptystack.pop() — returns undefined
Peekstack[-1]stack[stack.length - 1]
Enqueuequeue.append(x)queue.push(x)
Dequeuequeue.popleft() (deque)index-based read, or swap arrays

That difference in pop behaviour on an empty container shows up repeatedly: Python needs an explicit emptiness check where TypeScript's undefined falls through harmlessly.

All Problems

ProblemDifficultyPattern
Valid ParenthesesEasyStack
Min StackMediumAugmented Stack
Evaluate Reverse Polish NotationMediumStack
Simplify PathMediumStack

On this page