← Learning Hub
Intermediate

Stacks and Queues

A stack is last-in, first-out (LIFO), like a pile of plates. A queue is first-in, first-out (FIFO), like a line at a ticket counter.

Stacks and queues control the order in which work is done. A stack (last in, first out) powers undo buttons, browser back, and bracket checking. A queue (first in, first out) handles waiting lines - print jobs, orders, BFS in graphs.

Example
You can edit this code.
Use deque for queues: list.pop(0) is O(n), deque.popleft() is O(1).

Valid brackets (stack)

Example
You can edit this code.

Next greater element (monotonic stack)

Example
You can edit this code.

Each index is pushed and popped once, so this is O(n) - much better than checking every pair.

Key points
  • Stack: LIFO - append and pop.
  • Queue: FIFO - use collections.deque.
  • Monotonic stacks solve 'next greater' problems in O(n).

📝 Test yourself

1. Which structure is first-in, first-out?
2. Why use deque instead of a list for a queue?
3. Fill in the list method that removes the top of a stack:
top = stack.()