Skip to content
Lesson 5 of 10 · Coding Interview Prep: Data Structures and Algorithms

Stacks and queues

Use last-in-first-out and first-in-first-out containers for matching, undo and ordering problems.

22 min

A stack is last-in, first-out (LIFO): like a pile of plates, you add and remove at the top. A queue is first-in, first-out (FIFO): like a line at a till.

A list is a good stack: append() pushes and pop() removes the last item, both O(1). stack[-1] peeks at the top.

A list is a bad queue: pop(0) is O(n) because every item shifts. Use collections.deque:

python4 lines
from collections import deque
q = deque()
q.append("a")        # enqueue at the back
q.popleft()          # dequeue from the front, O(1)

Problems about matching or the most recent thing: brackets, nested tags, undo, evaluating expressions, "next greater element". The test is: do I need to deal with the latest unfinished item first?

Balanced brackets:

python9 lines
pairs = {")": "(", "]": "[", "}": "{"}
stack = []
for ch in s:
    if ch in "([{":
        stack.append(ch)
    elif ch in pairs:
        if not stack or stack.pop() != pairs[ch]:
            return False
return not stack      # nothing left open

Three failure cases: a closer with nothing to match, a closer of the wrong type, and openers left over at the end.

In 3 4 + 2 * operators come after their operands. Read left to right: push numbers; on an operator, pop two, compute, push the result. Order matters for -: the first value popped is the right operand.

Problems about processing in arrival order or level by level: task schedulers, "visit all neighbors first" (breadth-first search, coming in the tree lesson).

Two containers, one rule each.

Stack

Order out
last in, first out
Python tool
list: append, pop
Typical problem
brackets, undo, expression evaluation

Best for matching and nesting

Queue

Order out
first in, first out
Python tool
collections.deque: append, popleft
Typical problem
schedulers, breadth-first search

Best for fair order, level by level

Exercise8 checks
python

Write is_balanced(s). The string may contain (), [], {} and any other characters, which you ignore. Return True if every bracket is closed by the matching type in the right order.

is_balanced("{[()]}") is True; is_balanced("([)]") is False.

Your code must satisfy

  • is_balanced("{[()]}")→truenested
  • is_balanced("([)]")→falsewrong order
  • is_balanced("")→trueempty
  • is_balanced(")")→falseonly closer
  • is_balanced("((")→falseleft open
  • is_balanced("f(a[1], {b: 2})")→trueother characters
starter code2 lines
def is_balanced(s):
    pass
Exercise5 checks
python

Write evaluate_rpn(tokens). tokens is a list of strings: integers such as "3" or "-2", and the operators "+", "-", "*". Return the integer result of the postfix expression. You can assume it is valid.

evaluate_rpn(["3", "4", "+", "2", "*"]) is 14.

Your code must satisfy

  • evaluate_rpn(["3", "4", "+", "2", "*"])→14add then multiply
  • evaluate_rpn(["10", "3", "-"])→7subtraction order
  • evaluate_rpn(["42"])→42single number
  • evaluate_rpn(["-2", "5", "*"])→-10negative numbers
  • evaluate_rpn(["2", "3", "4", "*", "+", "5", "-"])→9nested
starter code2 lines
def evaluate_rpn(tokens):
    pass
Common misconception

“`list.pop(0)` is a fine way to take from the front of a queue.”

It works and gives the right answer on small tests.

What is actually true

pop(0) shifts every remaining item, costing O(n) each time, so a queue of n items takes O(n²). deque.popleft() is O(1).

How to catch yourself

Whenever you remove from the front repeatedly, import `deque`.

  • A stack is last-in, first-out; use a list with append and pop.
  • A queue is first-in, first-out; use collections.deque with append and popleft.
  • Reach for a stack for matching, nesting, undo and expression evaluation.
  • Check three failure cases in matching problems: closer with no opener, wrong type, openers left over.
Check yourself

Stack and queue checks.

1Multiple choice

After pushing 1, 2, 3 onto a stack and popping once, what is popped?

  • A1
  • B2
  • C3
  • DNothing
2Multiple choice

After enqueueing 1, 2, 3 and dequeuing once, what is dequeued?

  • A1
  • B2
  • C3
  • DNothing
3Multiple choice

Which is False?

  • A`is_balanced("()")`
  • B`is_balanced("(]")`
  • C`is_balanced("")`
  • D`is_balanced("[{}]")`
4Multiple choice

Why use deque for a queue?

  • AIt sorts items
  • B`popleft` is O(1) while `list.pop(0)` is O(n)
  • CIt stores numbers only
  • DLists cannot hold strings
5Numeric answer

What is the result of RPN 5 1 2 + 4 * + 3 -? (tokens in that order)

Practise this lesson, not just read it

In BiliMind the questions above are marked when you answer, the flashcards come back on a schedule, and the rest of Coding Interview Prep: Data Structures and Algorithms is planned around your week. Free.