Skip to content

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 variants

Matching and nesting

0 of 4 solved

Design with stacks

0 of 4 solved

Expression evaluation

0 of 4 solved

Monotonic stack

0 of 9 solved

Cancel and simulate

0 of 7 solved

Queues

0 of 3 solved

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.

Daily Temperatures with a stack of waiting days
73
0
↑i
74
1
75
2
71
3
69
4
72
5
76
6
stack = [0]answer = [0, 0, 0, 0, 0, 0, 0]

Day 0 (73) has nothing to compare with yet. Push its index: it is waiting for a warmer day.

1/6

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.

Quick check
Daily Temperatures has a while loop that pops inside a for loop over n days. What is the total running time?
Need a nudge? A hint rules out a wrong answer.

How to recognise it

Wording clues

Phrase in the promptWhat 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

ConstraintWhat it suggests
n up to 10^5 or moreO(n²) is too slow. A stack pass is O(n).
n up to 10^4O(n²) is borderline (10^8). Interviewers still expect the O(n) stack.
s.length <= 30 or <= 100The 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 allowedDo not use 0 or -1 as a sentinel value; use infinity or an empty-stack check.

Input and output shape clues

ShapeWhat it suggests
A string of brackets, maybe with lettersMatching 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 operatorsExpression evaluation.
A list of commands ("C", "../", "*")Simulate on a stack; each command adds or removes the latest item.
A class with methods called many timesDesign with stacks (or a queue).

Looks like it but isn't

Tempting patternWhy it is not a stack problem (or is)
Two pointersValid 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 mapCounts lose order. "([)]" has perfectly balanced counts and is still invalid.
HeapA 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 programmingLongest 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.
Quick check
Which prompt is the strongest signal for a monotonic stack?
Need a nudge? A hint rules out a wrong answer.

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.

Valid Parentheses on {[()]}
{
0
↑i
[
1
(
2
)
3
]
4
}
5
stack = {

Openers go on the stack.

1/4
Python
def is_valid(s: str) -> bool: 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 print(is_valid("{[()]}"))print(is_valid("([)]"))print(is_valid("(("))
Output
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.

Asteroid Collision on [10, 2, -5]
10
0
↑i
2
1
-5
2
stack = [10]

10 moves right. Push it.

1/4
Python
def remove_duplicates(s: str) -> str: kept = [] for ch in s: if kept and kept[-1] == ch: kept.pop() # the new letter cancels the latest survivor else: kept.append(ch) return "".join(kept) print(remove_duplicates("abbaca"))print(remove_duplicates("abccba"))
Output
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.

Predict the outputPython

What does this print?

kept = []
for ch in "ab*c**d":
  if ch == "*":
      kept.pop()
  else:
      kept.append(ch)
print("".join(kept))
Need a nudge? Hints walk you through it.

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 topPop when the new value is...
next greaterdecreasinggreater than the top
next smallerincreasingsmaller than the top
previous greater / smallersame stacksread the element below after pushing, or scan right to left
Largest Rectangle in Histogram on [2, 1, 5, 6, 2, 3]
2
0
1
1
↑i
5
2
6
3
2
4
3
5
stack = [1]best = 2

1 is shorter than 2, so bar 0 is done: it spans only itself, area 2 × 1 = 2. The stack keeps increasing heights.

1/4
Python
def next_greater(nums: list[int]) -> list[int]: answer = [-1] * len(nums) stack = [] # indices, values decreasing upward for i, x in enumerate(nums): while stack and nums[stack[-1]] < x: answer[stack.pop()] = x # x is the first bigger value to its right stack.append(i) return answer print(next_greater([2, 1, 2, 4, 3]))print(next_greater([5, 4, 3]))
Output
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]?"

Quick check
In Daily Temperatures, what goes wrong if you pop while temperatures[top] <= today instead of <?
Need a nudge? A hint rules out a wrong answer.

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.

Evaluate RPN on [2, 1, +, 3, *]
2
0
1
1
↑i
+
2
3
3
*
4
stack = [2, 1]

Numbers are pushed. Nothing to compute yet.

1/4
Python
def decode_string(s: str) -> str: saved = [] # (text before "[", repeat count) current, count = "", 0 for ch in s: if ch.isdigit(): count = count * 10 + int(ch) elif ch == "[": saved.append((current, count)) current, count = "", 0 elif ch == "]": before, times = saved.pop() current = before + current * times else: current += ch return current print(decode_string("3[a2[c]]"))print(decode_string("2[ab]x"))
Output
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.

Predict the outputPython

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])
Need a nudge? Hints walk you through it.

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.

Min Stack after push -2, push 0, push -3
  1. (-3, min -3) ← top
  2. (0, min -2)
  3. (-2, min -2) ← bottom

Push -2. The stack was empty, so the minimum so far is -2 itself.

1/4
Python
class StockSpanner: def __init__(self) -> None: self.stack = [] # (price, span) with prices decreasing upward def next(self, price: int) -> int: span = 1 while self.stack and self.stack[-1][0] <= price: span += self.stack.pop()[1] self.stack.append((price, span)) return span s = StockSpanner()print([s.next(p) for p in [100, 80, 60, 70, 60, 75, 85]])
Output
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.

Number of Recent Calls: the queue is the last 3000 ms
1
0
↑head
100
1
3001
2
3002
3
t = 1count = 1

ping(1): the range is [-2999, 1]. The queue holds just 1.

1/4
Python
class MyQueue: def __init__(self) -> None: self.inbox, self.outbox = [], [] def push(self, x: int) -> None: self.inbox.append(x) def pop(self) -> int: if not self.outbox: # refill only when empty while self.inbox: self.outbox.append(self.inbox.pop()) return self.outbox.pop() q = MyQueue()q.push(1); q.push(2)print(q.pop())q.push(3)print(q.pop(), q.pop())
Output
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 it in order5 steps

Put the questions in the order you should ask them when a problem smells like a stack.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.
Match the pairs0/6 matched

Match each problem to its sub-pattern.

Choose an item, then its match on the other side.

Traps

  • Popping an empty stack. In Python [].pop() raises an IndexError; in TypeScript it quietly returns undefined, which then compares wrongly. Check if stack (or stack.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 (0 or -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 - b and a / b break if you swap them.
  • Division rounding. Python's // floors (-7 // 2 is -4); these problems want truncation toward zero, so use int(a / b). In TypeScript use Math.trunc(a / b).
  • Multi-digit numbers. Build numbers with num = num * 10 + digit; 10[a] and 123+4 break if you read one digit at a time.
  • Using a list as a queue. list.pop(0) and Array.prototype.shift() are O(n). Use deque or 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.

Quick check
What does this Remove K Digits attempt return for 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"
Need a nudge? A hint rules out a wrong answer.
Key terms
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.deque in 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.