Algorithms Playbook
Data structureTime O(1)/op · Space O(n)7 min read

Stacks and queues: last-in-first-out and first-in-first-out

The two simplest ordered containers, what each one is for, and the classic bracket-matching problem that every candidate should be able to write.

In short

A stack gives back the most recent item first (LIFO); a queue gives back the oldest first (FIFO). Both do push and pop in O(1). Nested structure → stack. Processing in order of arrival → queue.

Two shapes, two jobs

Stack (LIFO)

  • Undo history, browser back button
  • The call stack of recursion
  • Matching brackets, evaluating expressions
  • DFS (depth-first search)

Queue (FIFO)

  • Print jobs, task queues
  • Level by level (BFS)
  • Streams of events in order
  • Rate limiting windows

In Python use a list as a stack and collections.deque as a queue. In Java use ArrayDeque for both. A JavaScript array works as a stack; for a queue shift() is O(n), so use an index or a deque.

The classic: matching brackets

Whenever structure is nested (brackets, HTML tags, function calls) the thing that closes first is the thing that opened last: a stack.

A stack of brackets: is the string valid?
Example
Speed
0{1[2(3)4]5}

stack

1def is_valid(s):
2 pairs = {')': '(', ']': '[', '}': '{'}
3 stack = []
4 for ch in s:
5 if ch in pairs:
6 if not stack or stack.pop() != pairs[ch]:
7 return False
8 else:
9 stack.append(ch)
10 return not stack
Every opening bracket waits on the stack; a closing one must match the most recent opener, the top.

Variables

stack[ ]
Step 1/14· Chars read: 0
A stack is last-in, first-out: the bracket you opened last must be the first one you close. Push is O(1), pop is O(1).

Where else it shows up

  • Implement a queue with two stacks (and the reverse): a classic design question.
  • Min stack: also keep the minimum so far with each element to answer "what's the min?" in O(1).
  • Evaluate reverse Polish notation: push numbers, on an operator pop two and push the result.
  • Replace recursion with an explicit stack to avoid stack overflow on deep inputs.

Key takeaways

  • 01Stack = LIFO, queue = FIFO; push and pop are O(1).
  • 02Nested or matching structure points to a stack.
  • 03Level-by-level or arrival order points to a queue.
  • 04An explicit stack can replace recursion.

Check your understanding

1 of 3

Which structure returns the most recently added item first?

Related topics