Stack
Reach for it when the problem says
- Matching brackets
- undo
- next greater element
- evaluate expressions
- Solved
- 0/31Solved
- Problems
- 31Problems
- Variants
- 6Variants
Problems
6 variantsMatching and nesting
0 of 4 solvedDesign with stacks
0 of 4 solved- Baseball GameEasyDecode Baseball Game
- Min StackSprintDeep diveMediumDecode Min Stack
- Online Stock SpanEssentialsDeep diveMediumDecode Online Stock Span
- Binary Search Tree IteratorSprintDeep diveMediumDecode Binary Search Tree Iterator
Expression evaluation
0 of 4 solved- Evaluate Reverse Polish NotationSprintDeep diveMediumDecode Evaluate Reverse Polish Notation
- Decode StringEssentialsDeep diveMediumDecode Decode String
- Basic Calculator IIMediumDecode Basic Calculator II
- Basic CalculatorSprintDeep diveHardDecode Basic Calculator
Monotonic stack
0 of 9 solved- Next Greater Element IDeep diveEasyDecode Next Greater Element I
- Daily TemperaturesEssentialsDeep diveMediumDecode Daily Temperatures
- Car FleetDeep diveMediumDecode Car Fleet
- Next Greater Element IIDeep diveMediumDecode Next Greater Element II
- Remove K DigitsMediumDecode Remove K Digits
- Sum of Subarray MinimumsMediumDecode Sum of Subarray Minimums
- 132 PatternMediumDecode 132 Pattern
- Largest Rectangle in HistogramDeep diveHardDecode Largest Rectangle in Histogram
- Maximal RectangleDeep diveHardDecode Maximal Rectangle
Cancel and simulate
0 of 7 solved- Remove All Adjacent Duplicates In StringEasyDecode Remove All Adjacent Duplicates In String
- Make The String GreatEasyDecode Make The String Great
- Crawler Log FolderEasyDecode Crawler Log Folder
- Removing Stars From a StringEssentialsDeep diveMediumDecode Removing Stars From a String
- Asteroid CollisionEssentialsDeep diveMediumDecode Asteroid Collision
- Simplify PathSprintDeep diveMediumDecode Simplify Path
- Validate Stack SequencesMediumDecode Validate Stack Sequences
Queues
0 of 3 solved- Implement Queue using StacksDeep diveEasyDecode Implement Queue using Stacks
- Number of Recent CallsEssentialsDeep diveEasyDecode Number of Recent Calls
- Dota2 SenateEssentialsDeep diveMediumDecode Dota2 Senate
Pattern guide
Stack problems show up constantly in interviews because the brute force is usually a nested loop or a "rescan after every change" loop, and the fix is one pass with a list you only touch at the end. Once you can name the sub-pattern in the first minute (matching, cancelling, monotonic, evaluating, designing, or really a queue), the code is short and the complexity argument is always the same: every item is pushed once and popped at most once.
What it is
A stack is a list where you only add and remove at one end, the top. The last thing you pushed is the first thing you pop: last in, first out (LIFO). In Python that is a plain list with append and pop; in TypeScript, an array with push and pop. Both are O(1).
The reason stacks solve so many problems is that a lot of questions only ever care about the most recent thing that is still unresolved: the latest open bracket, the latest folder you entered, the latest day still waiting for a warmer one. When an answer depends on "the most recent unfinished thing", you want a stack.
Here is the most famous example, Daily Temperatures: for each day, how many days until a warmer one? The stack holds the indices of days still waiting. Watch how a warm day resolves several waiting days at once.
Day 0 (73) has nothing to compare with yet. Push its index: it is waiting for a warmer day.
That inner while loop can pop many items in one step, but each index can only be popped once in its life. So across the whole scan the pops add up to at most n, and the total work is O(n), not O(n²). You will use that argument for nearly every problem on this page.
while loop that pops inside a for loop over n days. What is the total running time?How to recognise it
Wording clues
| Phrase in the prompt | What it implies |
|---|---|
| "valid parentheses", "balanced", "properly nested", "matching" | Each closer pairs with the latest open opener. Stack of openers (or their indices). |
| "next greater", "next warmer", "next smaller", "previous smaller" | Nearest element to one side that beats you. Monotonic stack. |
| "how many days until", "span", "how far back" | Distance to the nearest bigger or smaller value. Monotonic stack of indices. |
| "backspace", "undo", "cancel the previous", "remove adjacent" | New items can erase the most recent survivor. Push, and pop when they cancel. |
| "collide", "destroy", "explode" | A new item fights the latest survivors until it loses or the stack runs out. |
"evaluate", "calculator", "expression", "decode k[...]" | Postpone work until an operator or closing bracket arrives. Stack of values or saved states. |
| "design a class", "in O(1)", "getMin" | Store extra data next to each pushed item. |
| "in order of arrival", "first come", "last N milliseconds", "rounds" | First in, first out. That is a queue, the stack's sibling. |
Constraint clues
| Constraint | What it suggests |
|---|---|
n up to 10^5 or more | O(n²) is too slow. A stack pass is O(n). |
n up to 10^4 | O(n²) is borderline (10^8). Interviewers still expect the O(n) stack. |
s.length <= 30 or <= 100 | The input is tiny. Correctness and clean modelling matter more than speed. |
"at most 3 * 10^4 calls" | A design question: every method should be O(1) or amortised O(1). |
"each t is strictly larger" | Data arrives sorted by time, so expired items leave from the front: a queue. |
Values up to 10^9, negatives allowed | Do not use 0 or -1 as a sentinel value; use infinity or an empty-stack check. |
Input and output shape clues
| Shape | What it suggests |
|---|---|
| A string of brackets, maybe with letters | Matching and nesting. |
| An array, output an array of the same length ("for each i...") | Monotonic stack: each position gets its nearest bigger or smaller neighbour. |
| An array, output one number built from "every subarray" | Monotonic stack with contribution counting (how many subarrays is arr[i] the min of?). |
| A string of tokens or digits and operators | Expression evaluation. |
A list of commands ("C", "../", "*") | Simulate on a stack; each command adds or removes the latest item. |
| A class with methods called many times | Design with stacks (or a queue). |
Looks like it but isn't
| Tempting pattern | Why it is not a stack problem (or is) |
|---|---|
| Two pointers | Valid Parentheses is not about the two ends: "()[]" starts with ( and ends with ]. Matching follows nesting, not position from the ends. |
| Sliding window | "Next greater" has no window: the answer can be any distance away. But if you need the max of every window of size k, that is a monotonic deque, which belongs to sliding window. |
| Counting with a hash map | Counts lose order. "([)]" has perfectly balanced counts and is still invalid. |
| Heap | A heap gives the biggest value overall. A monotonic stack gives the nearest bigger value. If the question says "next", "previous" or "nearest", reach for the stack. |
| Dynamic programming | Longest Valid Parentheses and Sum of Subarray Minimums both have DP solutions, but the stack versions are simpler and the DP ones are built on the same previous-smaller idea. |
The sub-patterns
Matching and nesting
When it applies: the input is nested (brackets, tags, folders inside folders), and every closer must pair with the most recent opener that is still open. Push openers; on a closer, pop and check. When you need lengths or positions (Longest Valid Parentheses, Minimum Remove), push indices instead of characters. When a score depends on what is inside a pair (Score of Parentheses), push a running total per nesting level.
Openers go on the stack.
Press Run (⌘ Enter) to see what happens.Press Run (⌘ Enter) to see what happens.Complexity: O(n) time, O(n) space in the worst case (all openers).
Best-known problems: Valid Parentheses, Longest Valid Parentheses, Minimum Remove to Make Valid Parentheses, Score of Parentheses.
The index-stack trick for Longest Valid Parentheses
Seed the stack with -1. Push the index of every (. On ), pop. If the stack is now empty, this ) had no partner, so push its index as the new "wall". Otherwise the current valid run is i - stack[-1] long, because the top is the last position that is not part of the run. The -1 seed is the wall before the string starts.
Cancel and simulate
When it applies: you process items left to right, and a new item can cancel, absorb or destroy the latest survivor, which may expose an older survivor that it can fight next. Backspaces, adjacent duplicates, opposite-case pairs, colliding asteroids, .. in a file path, and checking whether a pop order is possible all fit. The stack holds the survivors so far, so at the end it is the answer.
10 moves right. Push it.
Press Run (⌘ Enter) to see what happens.Press Run (⌘ Enter) to see what happens.Complexity: O(n) time and O(n) space. Sometimes the stack collapses to a counter (Crawler Log Folder only needs the stack's size), giving O(1) space.
Best-known problems: Removing Stars From a String, Asteroid Collision, Simplify Path, Remove All Adjacent Duplicates In String, Validate Stack Sequences.
What does this print?
kept = []
for ch in "ab*c**d":
if ch == "*":
kept.pop()
else:
kept.append(ch)
print("".join(kept))Monotonic stack
When it applies: for each position you need the nearest element to one side that is bigger (or smaller). Keep a stack of indices whose values are monotonic (always decreasing, or always increasing, from bottom to top). When a new value breaks the order, it is the answer for everything it pops. This one idea covers next greater element, daily temperatures, stock spans, the largest rectangle in a histogram, sums over subarray minimums, and greedy digit removal.
Which way the stack is sorted depends on what you are looking for:
| You want, for each element... | Stack values from bottom to top | Pop when the new value is... |
|---|---|---|
| next greater | decreasing | greater than the top |
| next smaller | increasing | smaller than the top |
| previous greater / smaller | same stacks | read the element below after pushing, or scan right to left |
1 is shorter than 2, so bar 0 is done: it spans only itself, area 2 × 1 = 2. The stack keeps increasing heights.
Press Run (⌘ Enter) to see what happens.Press Run (⌘ Enter) to see what happens.Complexity: O(n) time, O(n) space. Circular inputs loop twice (i % n), still O(n). A 2D grid of rows runs one histogram per row: O(rows · cols).
Best-known problems: Daily Temperatures, Largest Rectangle in Histogram, Next Greater Element I and II, Car Fleet, Remove K Digits, Sum of Subarray Minimums.
Equal values: strict or non-strict pops
Ties are where monotonic stacks break. Daily Temperatures wants strictly warmer, so pop on <, not <=. Stock Span counts days that are less than or equal, so pop on <=. Sum of Subarray Minimums must not count a subarray twice when it has two equal minimums, so one boundary is strict and the other is not (popping on >= does that). Before coding, ask: "what happens with [2, 2, 2]?"
temperatures[top] <= today instead of <?Expression evaluation
When it applies: the input is an expression or an encoding where some work must wait: an operator waits for its operands (postfix), + and - wait for * and / (precedence), and a bracket waits for its closing partner (nesting). Push values, or push a saved state when you enter a bracket, and finish the work when the trigger arrives.
Numbers are pushed. Nothing to compute yet.
Press Run (⌘ Enter) to see what happens.Press Run (⌘ Enter) to see what happens.Complexity: O(n) time and space for calculators and RPN. Decoding is linear in the input plus the output.
Best-known problems: Evaluate Reverse Polish Notation, Basic Calculator, Basic Calculator II, Decode String.
What does this print? (Watch the pop order.)
stack = []
for tok in ["8", "3", "-", "2", "*"]:
if tok in "+-*":
b = stack.pop()
a = stack.pop()
stack.append(a - b if tok == "-" else a * b if tok == "*" else a + b)
else:
stack.append(int(tok))
print(stack[0])Design with stacks
When it applies: you build a class whose methods are called many times, and each must be O(1) or amortised O(1). The trick is almost always to store extra information next to each pushed item, computed once at push time, because a stack only changes at the top, so whatever you knew about the items below never goes stale. Min Stack stores the minimum so far; Stock Spanner stores how many days each entry already covers; Baseball Game keeps the record on a stack so "C" can undo the latest score.
Push -2. The stack was empty, so the minimum so far is -2 itself.
Press Run (⌘ Enter) to see what happens.Press Run (⌘ Enter) to see what happens.Complexity: O(1) per operation (amortised for Stock Spanner), O(n) space.
Best-known problems: Min Stack, Online Stock Span, Baseball Game.
Queues
When it applies: items leave in the order they arrived: first in, first out (FIFO). Requests expire oldest first (Number of Recent Calls), players take turns in rounds (Dota2 Senate), or you are asked to build a queue out of stacks. Use collections.deque in Python (append and popleft are both O(1); list.pop(0) is O(n)). In TypeScript, shift() is O(n) on large arrays, so keep a head index instead.
ping(1): the range is [-2999, 1]. The queue holds just 1.
Press Run (⌘ Enter) to see what happens.Press Run (⌘ Enter) to see what happens.Complexity: O(1) amortised per operation. Each item enters and leaves each structure once.
Best-known problems: Implement Queue using Stacks, Number of Recent Calls, Dota2 Senate.
Decision checklist
Ask these questions in order. The first "yes" usually names the sub-pattern.
Put the questions in the order you should ask them when a problem smells like a stack.
- Tap the steps below in the right order.
Match each problem to its sub-pattern.
Traps
- Popping an empty stack. In Python
[].pop()raises anIndexError; in TypeScript it quietly returnsundefined, which then compares wrongly. Checkif stack(orstack.length > 0) before every pop unless the problem guarantees it. - Forgetting the final check. Valid Parentheses must also confirm the stack is empty at the end, or
"(("passes. - Leftovers after the scan. In monotonic stacks, items still on the stack never found an answer. Initialise answers to the default (
0or-1) or flush with a sentinel (a height-0 bar in Largest Rectangle). - Pushing values when you need indices. If the answer is a distance, a width or a position, push indices and look values up.
- The wrong tie rule. Decide strict versus non-strict from the wording ("strictly warmer" versus "less than or equal").
- Operand order. In RPN the first pop is the right operand.
a - banda / bbreak if you swap them. - Division rounding. Python's
//floors (-7 // 2is-4); these problems want truncation toward zero, so useint(a / b). In TypeScript useMath.trunc(a / b). - Multi-digit numbers. Build numbers with
num = num * 10 + digit;10[a]and123+4break if you read one digit at a time. - Using a list as a queue.
list.pop(0)andArray.prototype.shift()are O(n). Usedequeor a head index. - Refilling the outbox too early. In Queue using Stacks, pour the inbox over only when the outbox is empty, or newer items jump ahead of older ones.
Edge cases to always test: the empty input (if allowed), a single element, all-equal values, strictly increasing and strictly decreasing input, and an input where nothing ever pops.
num = '12345', k = 2?def remove_kdigits(num, k):
stack = []
for d in num:
while k and stack and stack[-1] > d:
stack.pop()
k -= 1
stack.append(d)
return "".join(stack).lstrip("0") or "0"- Stack (LIFO)
- A list you only push to and pop from at one end, the top. The last item in is the first out. Push, pop and peek are O(1).
- Monotonic stack
- A stack whose values stay sorted from bottom to top. A new value pops everything it beats, and is the nearest greater (or smaller) element for each item it pops.
- Amortised O(1)
- An operation that is occasionally slow but cheap on average, because the total work over any sequence of n operations is O(n). Every item is pushed and popped at most once.
- Sentinel
- A fake value added to the input or the stack (a -1 base index, a height-0 bar) so edge cases are handled by the main loop instead of extra code.
- Queue (FIFO)
- A line where items leave in arrival order. Use
collections.dequein Python or a head index in TypeScript for O(1) removal from the front. - Postfix (RPN)
- Notation where operators come after their operands, like
3 4 +. Evaluated with a stack: push numbers, and let each operator pop two values and push the result.