CS concepts
Stacks and the Monotonic Stack Explained: 5 Interview Problems
Updated Nov 28, 2026 · 4 min read
A stack is last in, first out: you push on top, pop off the top and peek at the top, all in O(1). Reach for one whenever the most recent thing matters most, like matching brackets or evaluating expressions. A monotonic stack keeps items in sorted order and pops them as soon as they find their answer, which turns n-squared scans like Daily Temperatures and Largest Rectangle in Histogram into one O(n) pass.

Key points
- ●Push, pop and peek are all O(1); in Python a plain list is a stack.
- ●Valid Parentheses: push openers, pop on closers, and the stack must end empty.
- ●Min Stack: store each value with the minimum at that moment.
- ●A monotonic stack holds items still waiting for an answer, so each item is pushed and popped once: O(n).
- ●Traps: popping an empty stack, forgetting the leftovers, storing values instead of indexes.

What a stack is
The last plate you put on the pile is the first one you take off. That's a stack: last in, first out.
A stack does three things, all O(1): push something on top, pop the top off, and peek at the top without taking it. Nothing else. No reaching into the middle.
In Python you don't need a special class. A plain list is a stack: append pushes, pop() takes the last item, and stack[-1] peeks.
You already use stacks: the back button, undo, and Python's call stack, which is why very deep recursion runs out of room.
If the most recent thing matters most, think stack.
Problem 1: Valid Parentheses (LeetCode 20)
You get a string of round, square and curly brackets. Is every one closed by the right type, in the right order? The last bracket you opened must be the first one you close, which is last in, first out.
def is_valid(s):
pairs = {")": "(", "]": "[", "}": "{"}
stack = []
for ch in s:
if ch in pairs:
if not stack or stack.pop() != pairs[ch]:
return False
else:
stack.append(ch)
return not stack
Try ( [ ) ]. The round closer arrives while [ is on top. Wrong partner, so it's not valid. And the last line matters: (( never hits a wrong partner, but it leaves the stack full, so it's not valid either. One pass, O(n).
Problem 2: Min Stack (LeetCode 155)
Build a stack that also returns its smallest value, with every operation O(1). One variable breaks when you pop the minimum. So each item remembers: store the value and the minimum at that moment as a pair.
def push(self, x):
low = min(x, self.stack[-1][1]) if self.stack else x
self.stack.append((x, low))
def get_min(self):
return self.stack[-1][1]
Push 5, 3, 7. The pairs say 5, 3, 3. Pop twice and the top pair says 5. The old minimum came back by itself.
Problem 3: Evaluate Reverse Polish Notation (LeetCode 150)
Here the operator comes after the numbers: 2 1 + 3 * means (2 + 1) times 3. Numbers go on the stack, and each operator pops two, does the math and pushes the result.
def eval_rpn(tokens):
ops = {"+": lambda a, b: a + b, "-": lambda a, b: a - b,
"*": lambda a, b: a * b, "/": lambda a, b: int(a / b)}
stack = []
for t in tokens:
if t in ops:
b, a = stack.pop(), stack.pop()
stack.append(ops[t](a, b))
else:
stack.append(int(t))
return stack[0]
2 1 + leaves 3, then 3 * gives 9. The first pop is the right-hand number, so swapping them breaks subtraction. And the problem wants division cut toward zero: Python's // rounds down, so -7 // 2 is -4, while int(-7 / 2) is -3.
Stack or queue?
A queue is first in, first out. Stacks go deep, queues go wide: depth-first vs breadth-first search. In Python, use collections.deque with append and popleft, both O(1), never a plain list.
Problem 4: Daily Temperatures (LeetCode 739)
For each day, how many days until a warmer one? Checking every later day is O(n²), about 66 thousand checks for a year of data.
The monotonic stack keeps the days still waiting for a warmer one. Their temperatures only go down as you go up the stack. A warmer day pops every colder day off the top, and each popped day has found its answer: the gap.
def daily_temperatures(t):
ans = [0] * len(t)
stack = []
for i, x in enumerate(t):
while stack and t[stack[-1]] < x:
j = stack.pop()
ans[j] = i - j
stack.append(i)
return ans
On 73 74 75 71 69 72 76 73, 72 arrives and pops 69 (1 day) and 71 (2 days). Then 76 pops 72 and 75 (4 days). The result is [1, 1, 4, 2, 1, 1, 0, 0]. Every day goes on once and comes off once, so it's O(n). Store indexes, not temperatures, because the answer is a distance.
Problem 5: Largest Rectangle in Histogram (LeetCode 84)
Bars of height 2 1 5 6 2 3. What's the biggest rectangle under them? This time the stack keeps bars in increasing height. A bar can stretch right until a shorter one shows up.
def largest_rectangle(heights):
stack, best = [], 0
for i, h in enumerate(heights + [0]):
while stack and heights[stack[-1]] > h:
top = stack.pop()
left = stack[-1] + 1 if stack else 0
best = max(best, heights[top] * (i - left))
stack.append(i)
return best
When the bar of height 2 arrives, 6 pops with area 6, then 5 pops and stretches across 5 and 6: height 5, width 2, area 10. The extra 0 at the end is a sentinel that forces every leftover bar to pop. The sheets above trace these problems step by step.
The traps
- Popping an empty stack. A closer with nothing open crashes. Check
if not stackfirst. - Forgetting the leftovers. Unclosed brackets, unpopped bars, days with no warmer day: what's left at the end matters.
- Values when you need indexes. If the answer is a distance, store positions.
pop(0)instead ofpop(). It takes from the front and shifts the whole list, turning your stack into a slow queue.
Frequently asked questions
What is a monotonic stack?
A stack whose items always stay in order, either increasing or decreasing from bottom to top. When a new item would break the order, you pop items until it fits, and each popped item has just found its answer, such as its next warmer day.
Why is the monotonic stack O(n) when it has a loop inside a loop?
Each index is pushed once and popped at most once across the whole run. The inner while loop can't pop more items in total than were pushed, so the total work is O(n).
Stack vs queue: what is the difference?
A stack is last in, first out, like a pile of plates. A queue is first in, first out, like a line at a shop. Stacks go deep (depth-first search), queues go wide (breadth-first search). In Python, use a list for a stack and collections.deque for a queue.
How do I make a stack in Python?
Use a plain list. append pushes, pop() takes the last item, and stack[-1] peeks. Don't use pop(0), which takes from the front and shifts the whole list every time.