Skip to content
TOPIC · 14 PROBLEMS · 5 PATTERNS

Stacks

The last thing in is the first thing out. Perfect for anything that opens and must later close, or that waits until something better comes along.

How to spot a stack problem

“valid / balanced”Brackets, tags or anything that must close in the reverse order it opened. Push on open, pop and compare on close.
“next greater”For each element, find the first one after it that beats it. That is a monotonic stack, nearly word for word.
“nested”Structures inside structures, like 3[a2[c]]. A stack holds the outer level while you deal with the inner one.
“collide / cancel”New items can wipe out recent ones, which can then expose older ones. Only the top of the pile is ever touched.

Five patterns cover almost everything

Matching pairs

O(n)

Push every opener. On a closer, the top of the stack must be its partner. At the end the stack must be empty.

Reach for it when things open and close and must nest properly.

Nested levels

O(n)

When a new level opens, push what you have so far and start fresh. When it closes, pop the outer state and fold the inner result into it.

Reach for it when the input nests, and you would otherwise reach for recursion.Go deeper: What the call stack does during recursion

Expression evaluation

O(n)

Keep numbers on a stack. An operator pops its operands and pushes the result. Delay addition so multiplication can bind first.

Reach for it when you are evaluating arithmetic, postfix notation, or a small calculator.

Collapse the top

O(n)

Compare each new item only with the top. If they cancel, pop and compare again with the new top. Otherwise push.

Reach for it when neighbours can destroy each other and the survivors form the answer.Go deeper: Amortised cost: why push is O(1) on average

Monotonic stack

O(n)

Keep the stack in decreasing order. A new value pops everything smaller, and it is the answer every popped item was waiting for.

Reach for it when each element needs the next or previous larger or smaller element, or the widest span it dominates.Go deeper: Amortised cost: why push is O(1) on average

The one template to memorise

Worth knowing cold: the monotonic stack. It looks quadratic because of the inner loop, but every index is pushed and popped once.

solution.py
def next_greater(nums):
answer = [-1] * len(nums)
stack = [] # indices still waiting, values decreasing
for i, x in enumerate(nums):
while stack and nums[stack[-1]] < x:
answer[stack.pop()] = x
stack.append(i)
return answer

Problems, easy to hard

Do them in order the first time
#ProblemPatternDifficultySolution
1Baseball GameStack simulationEasyRead
2Valid ParenthesesMatching pairsEasyRead
3Next Greater Element IMonotonic stackEasyRead
4Evaluate Reverse Polish NotationExpression evaluationMediumRead
5Asteroid CollisionCollapse the topMediumRead
6Daily TemperaturesMonotonic stackMediumRead
7Decode StringNested levelsMediumRead
8Next Greater Element IIMonotonic stackMediumRead
9Basic Calculator IIExpression evaluationMediumRead
10Car FleetMonotonic stackMediumRead
11Remove K DigitsMonotonic stackMediumRead
12Largest Rectangle in HistogramMonotonic stackHardRead
13Trapping Rain WaterMonotonic stackHardRead
14Basic CalculatorNested levelsHardRead
Next upHeapsIntervals