Stacks and Monotonic Stacks
A stack is last in, first out: the most recent thing you set aside is the first thing you come back to. That makes it the natural structure for anything nested (brackets, expressions, compressed strings) and for one of the most useful tricks in coding interviews: the monotonic stack, which answers "what is the next larger (or smaller) element?" for every position in a single pass.
This lesson is for software engineering and data candidates preparing for a live coding round. It covers both uses, with code, traces and the amortized argument that interviewers expect you to make. Code is in Python, where a list's append and pop are O(1) stack operations.
When the pattern fits
Nesting: brackets, tags, function calls, expressions with parentheses, strings like
2[a3[b]]. Whenever you must finish an inner thing before returning to the outer one, the outer one waits on a stack."Next greater", "previous smaller", "how many days until", "how far can this extend" for every element. These are monotonic stack problems.
Undo, backtracking through a path, or simplifying a sequence (removing adjacent duplicates, resolving
..in a file path).Iterative depth-first traversal, when recursion depth could be a problem.
Nested structure: matching brackets
Prompt: "Given a string of ()[]{} characters, return whether every bracket is closed in the right order."
Each opening bracket is a promise that must be kept before any older promise. Push openers; on a closer, the top of the stack must be its partner.
def balanced(s):
partner = {")": "(", "]": "[", "}": "{"}
stack = []
for ch in s:
if ch in "([{":
stack.append(ch)
elif ch in partner:
if not stack or stack.pop() != partner[ch]:
return False
return not stackThree edge cases cover most of the bugs: a closer with an empty stack (")(" must fail on the first character), a mismatch ("(]"), and leftovers ("((" must fail at the end, which is why the return is not stack rather than True). Naming those three before you are asked is the testing and edge cases score in one sentence.
Nested structure: expanding a compressed string
Prompt: "Expand strings like 3[ab]2[c] into abababcc. Brackets can nest: 2[a3[b]] becomes abbbabbb."
When you meet [, you are starting an inner string, and you must remember two things about the outer one: the text built so far and how many times to repeat the inner part. Push both; pop them at ].
def expand(s):
stack = []
current = []
count = 0
for ch in s:
if ch.isdigit():
count = count * 10 + int(ch) # counts can have several digits
elif ch == "[":
stack.append(("".join(current), count))
current, count = [], 0
elif ch == "]":
prefix, times = stack.pop()
current = [prefix + "".join(current) * times]
else:
current.append(ch)
return "".join(current)Trace 2[a3[b]]:
2: count is 2.[: push("", 2), start a new current string.a: current isa.3, then[: push("a", 3), start again.b: current isb.]: pop("a", 3), current becomesa+bbb=abbb.]: pop("", 2), current becomesabbbabbb.
The count * 10 line handles 12[x]; forgetting it is the most common bug in this problem, and a good edge case to test aloud. Time is at least the length of the output, which can be far larger than the input (and each nesting level copies its text once more); say so when you give the complexity.
Evaluating arithmetic with parentheses follows the same shape: at (, push the running total and the sign in front of the parenthesis; at ), pop them and combine.
Monotonic stacks: next greater element
Prompt: "Given daily prices, return for each day how many days you would wait for a strictly higher price, or 0 if it never comes."
The brute force scans forward from each day: O(n²) when prices mostly fall. The insight: keep a stack of days that are still waiting for a higher price. Their prices never increase from bottom to top, because any day with a lower price than a newer day would already have been answered by it. Equal prices both stay, since neither is strictly higher. When a new price arrives, it answers every waiting day with a lower price; pop them.
def days_until_higher(prices):
answer = [0] * len(prices)
waiting = [] # indexes; their prices never increase toward the top
for i, price in enumerate(prices):
while waiting and prices[waiting[-1]] < price:
j = waiting.pop()
answer[j] = i - j
waiting.append(i)
return answerTrace [5, 3, 4, 8, 6]:
Day 0 (5): stack
[0].Day 1 (3): 5 is not lower, push. Stack
[0, 1].Day 2 (4): pops day 1 (answer 1). 5 is not lower, push. Stack
[0, 2].Day 3 (8): pops day 2 (answer 1), then day 0 (answer 3). Stack
[3].Day 4 (6): 8 is not lower, push. Stack
[3, 4].
Result [3, 1, 1, 0, 0]. Days left on the stack never see a higher price and keep their default 0.
Two candidates who both finish this problem can score very differently. The weaker one writes the forward scan, is told it is too slow, then produces the stack version from memory without being able to say what the stack holds, and calls it O(n²) when asked. The stronger one states the brute force and when it degrades, says the stack sentence (what it holds and in what order) before coding (problem solving), stores indexes because the answer is a distance (code quality), traces the example above (correctness), tests a strictly falling and an all-equal input unprompted (testing and edge cases), and gives the push-once, pop-once argument for O(n) (communication).
Why it is O(n), not O(n²). The inner while can pop many items at once, so it looks quadratic. But each index is pushed exactly once and popped at most once over the whole run, so the total work across all iterations is at most 2n. This is an amortized argument, and interviewers ask for it often. Say "each element is pushed once and popped at most once" and you have answered it.
Four variants come from two choices:
Next greater or next smaller: flip the comparison (
<becomes>), which flips the stack from decreasing to increasing.To the right or to the left: for "previous greater", the answer for a new element is whatever is left on top of the stack after popping.
Strict or not:
<versus<=decides whether equal values count, which matters with duplicates. Decide it from the problem statement, not by accident.
Store indexes, not values. You can always read the value from the index, but not the other way around, and most answers are distances.
A harder monotonic stack problem
The classic stretch question is the largest rectangle under a histogram: for each bar, how far left and right can it extend before hitting a shorter bar? Those two boundaries are exactly "previous smaller" and "next smaller", so an increasing stack finds both in one pass, and the area for each bar is its height times the width between them. You do not need to memorize the code; recognizing that "how far can this extend" means "nearest smaller on each side" is the insight that earns the problem solving score, and the interviewer will often help with the details.
Tip
When you propose a monotonic stack, say what the stack holds and the order it keeps in one sentence: "indexes of days still waiting for a higher price, with prices never increasing toward the top." Every line of the loop follows from that sentence.
Follow-ups to expect
The AI interviewer lets you drive, then asks for your complexity and your tests, and on a monotonic stack it will almost always ask why the nested loop is linear. If you are stuck, the first hint is a nudge ("which days are still waiting for an answer?"); later hints name the stack. Each hint is counted against the dimension it helped with, the near-solution one most. After a working solution, expect:
"Design a stack that returns its minimum in O(1)." Keep a second stack (or a pair per entry) recording the minimum at each depth.
"Implement a queue with two stacks." Push onto an inbox; when the outbox is empty, move everything across. Each element moves at most once, so operations are amortized O(1), the same argument as above.
"The prices wrap around: the day after the last is the first." Loop over the array twice (indexes modulo n) and only push during the first pass.
"What if the input is huge?" The stack can hold n items in the worst case (strictly decreasing input). Say O(n) space.
What changes with seniority
Early-career candidates are expected to solve bracket matching cleanly and reach the monotonic stack with a hint. Mid-level candidates should recognize "next greater" wording without help and give the amortized argument unprompted. Senior candidates are expected to derive the variants (previous or next, greater or smaller, strict or not) on the spot and to see the histogram problem as two nearest-smaller searches.
Mistakes that cost points
Popping from an empty stack on an unmatched closer.
Returning
Truewithout checking the stack is empty at the end.Reading only one digit of a repeat count.
Storing values instead of indexes when the answer is a distance.
Claiming O(n²) for the monotonic loop, or claiming O(n) without the push-once, pop-once reason.
Practice it
Drill for 15 minutes: write days_until_higher from memory, then change it to "previous smaller element" for every position and trace both on [2, 7, 3, 1, 5]. Then write expand and test it on 12[x] and 2[a2[b]c] (which expands to abbcabbc).
Then take Design an LRU Cache as a live interview to practice the same habit this lesson drills: saying what each structure holds and what every operation costs, before you code. Previous in this series: Hash Maps and Prefix Sums. Next: Heaps and Top K.
Practise this in a mock interview
Try what this lesson covers out loud: the AI interviewer asks one of these questions, follows up, and scores your answer.
- Two SumCoding · Easy
- Design an LRU CacheCoding · Medium
- Deploy Services in Dependency WavesCoding · Medium
- Flag Overlapping Maintenance WindowsCoding · Medium
Read next
- Heaps and Top K
Recognize when a problem needs a heap, code its four shapes (top k, k-way merge, two heaps for a running median, scheduling by earliest end) and say when a plain sort or quickselect is the better answer.
9 min read
- Trees
Decide whether information flows down a tree as arguments or up as return values, then write correct DFS, level-order BFS and BST solutions, including iterative traversal for trees too deep for recursion.
9 min read
- Graphs
Model a problem as a graph and pick the right tool (BFS, DFS, topological sort, Dijkstra or union-find) while avoiding the visited-set and recursion-depth bugs that cost correctness points.
9 min read
- Backtracking: Searching Every Option Without Getting Lost
Spot 'list every answer' problems, apply one choose, explore, unchoose template to subsets, permutations, combinations and constraint puzzles, prune early, and state the exponential cost honestly.
9 min read
