Topic 3 of 8

Stacks and Queues for Coding Interviews

Stacks and queues explained with pictures: push, pop, bracket matching and the monotonic stack pattern, with a quiz and practice problems.

  • 2 min read
  • 5-question quiz
  • 3 practice problems

Stacks and queues are lists with rules about which end you add to and remove from. Those rules make some problems almost trivial: anything with nesting, undo, "the most recent unmatched thing", or processing in arrival order.

Stack: last in, first out

Push items on top, pop the top item off. Think of a stack of plates.

pushpopyou can onlyreach the top plate
A stack works like a pile of plates: the last one you put down is the first one you pick up.
OperationPython listJavaScript ArrayCost
Pushstack.append(x)stack.push(x)O(1)
Popstack.pop()stack.pop()O(1)
Peek at the topstack[-1]stack[stack.length - 1]O(1)
Is it empty?not stackstack.length === 0O(1)

Use a stack when the most recent thing you haven't finished with is the one that matters next: matching brackets, undo history, evaluating expressions, and depth-first search without recursion.

Push and pop1 / 3
3push
2top →1

Push 3: it goes on top.

Queue: first in, first out

Add at the back, remove from the front, like a line at a shop.

frontserved firstnew people joinat the back
A queue is a line at the coffee shop: first come, first served, and newcomers join at the back.
OperationPythonJavaScriptCost
Add to the backqueue.append(x) (with collections.deque)queue.push(x)O(1)
Remove from the frontqueue.popleft()queue[head++] (keep an index)O(1)

Use a queue when you process things in the order they arrived: breadth-first search, task scheduling, and streams of events.

Enqueue and dequeue1 / 3
ABC
frontback
Denqueue

D joins at the back.

?

OK, but when would a stack actually save me in an interview?

Pattern: matching pairs

For brackets, tags or anything that opens and closes: push each opener; when a closer arrives, it must match the opener on top of the stack, so pop it and compare. At the end, the stack must be empty (nothing left open).

Checking "( [ ] )"1 / 5
(push
empty

'(' opens: push it.

Pattern: the monotonic stack

A monotonic stack keeps its items in sorted order (for example, values decreasing from bottom to top). When a new item arrives, pop everything it "beats" first. Each popped item has just found its answer: the next bigger item is the one that popped it.

python
1answer = [0] * len(values)
2stack = []  # indexes whose next bigger value isn't known yet

indexes still waiting for an answer

3for i, v in enumerate(values):
4    while stack and values[stack[-1]] < v:

v beats the waiting values...

5        j = stack.pop()
6        answer[j] = i - j  # v is the next bigger value for j

...so v is their next bigger value

7    stack.append(i)

now v waits for its own answer

Every index is pushed once and popped at most once, so this is O(n), not O(n²). Look for monotonic stacks in "next greater", "previous smaller", "how many days until...", and skyline/histogram problems.

Next warmer value1 / 2
i
18
0
17
1
21
2
17top →18

18 and 17 wait on the stack: neither has met a bigger value yet.

Common mistakes

  • Popping from an empty stack: check if stack first, and decide what an unmatched closer means.
  • Forgetting the final check: a leftover opener means the input wasn't balanced.
  • Using list.pop(0) / shift() in a loop and turning an O(n) algorithm into O(n²).

Nice work!

You've got the big idea. Try the quick quiz below, then put it to work on the practice problems.

Quick quiz

5 questions. Pick an answer to see the explanation.

0/5
  1. 1You push 1, 2, 3 onto a stack, pop once, then push 4. What's on top?

  2. 2Which data structure fits breadth-first search, where you visit things in the order you discovered them?

  3. 3In Python, why use collections.deque for a queue instead of a list with pop(0)?

  4. 4Checking brackets in "( [ ) ]" with a stack: what happens at the ")"?

  5. 5In a monotonic stack solution, each index is pushed once and popped at most once. What's the total time for n items?

Practise what you learned

Solve them in your browser, in Python or JavaScript.

  1. Problem 1Check that a template's brackets are balancedeasy
  2. Problem 2Days until a warmer daymedium
  3. Problem 3Evaluate a calculator in postfix notationmedium