Python 3.11+
The examples use standard Python containers and syntax available in the supported browser runtime; Stack itself is taught as an interview abstraction.
Verify in Python docs(opens in a new tab)Last-in-first-out structure for nested state, expression evaluation, and iterative traversal. This guide turns that contract into deliberate Python operations, interview invariants, and a runnable practice loop.
Recognize it when
Consider Stack when the prompt's constraints and required operations match this shape: Last-in-first-out structure for nested state, expression evaluation, and iterative traversal.

Sign in to save your code and progress across devices. The lesson and problem statement remain public.
A stack exposes only the most recently pushed unfinished item. That LIFO boundary fits nested state, expression evaluation, and iterative traversal because new work must finish before older suspended work can resume. Items below the top form a compressed history in their exact return order.
Use append to push, pop to remove the top, and stack[-1] to peek. These operations are O(1)
amortized at the list’s right end. Avoid insert(0, value) and pop(0), which shift the remaining
references. The Python list reference(opens in a new tab)
also defines the IndexError raised by an unguarded pop from an empty stack.
For delimiters, the stack contains exactly the unmatched opening characters in the processed prefix. A closer must match the current top; finding a compatible opener deeper in the stack does not repair incorrectly nested inner state.
def is_balanced(text):
matching = {')': '(', ']': '[', '}': '{'}
opening = set(matching.values())
stack = []
for character in text:
if character in opening:
stack.append(character)
elif character in matching:
if not stack or stack.pop() != matching[character]:
return False
return not stackImplement is_balanced(text) for (), [], and {}. Ignore non-delimiter characters and require every closer to match the latest unmatched opener.
Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor
For adjacent cancellation, keep the fully reduced processed prefix on the stack. The next token creates only one possible new pair—with the top. Cancel that pair or push the token. Since each token is pushed once and popped at most once, cascading reductions still take O(n) total time.
def reduce_adjacent_pairs(tokens):
stack = []
for token in tokens:
if stack and stack[-1] == token:
stack.pop()
else:
stack.append(token)
return stackImplement reduce_adjacent_pairs(tokens). Cancel the current token with an equal stack top; otherwise push it, then return the reduced sequence.
Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor
Recursion already supplies a call stack and can be clearest for small, naturally recursive trees. Choose an explicit stack when depth may exceed Python’s recursion limit, frame state is small, or visit order needs direct control. Choose a queue when older work must be processed before newer work.
IndexError.State what one stack item represents and what the complete stack means after each input. Name the events that push and pop. Justify O(n) with aggregate accounting rather than claiming every loop body is identical: every item enters once and leaves at most once. Worst-case auxiliary space is O(n) when nothing resolves early.
Apply One Stack Reduction(opens in a new tab) isolates top interaction. Min Stack(opens in a new tab) adds synchronized metadata so minimum lookup remains O(1) without rescanning values.
Python 3.11+
The examples use standard Python containers and syntax available in the supported browser runtime; Stack itself is taught as an interview abstraction.
Verify in Python docs(opens in a new tab)Interview bounds depend on the stated representation, input model, and real Python operations.
| Operation | Average | Worst | Interview note |
|---|---|---|---|
| Core Stack workflow | O(n) | O(n) | When each new item can combine only with the most recent unresolved item, a stack represents exactly the pending state. The stack is the fully reduced form of the processed prefix and contains no adjacent equal pair. |
O(n) for the demonstrated Stack workflow.
These are the mistakes most likely to survive a happy-path example and fail a boundary case.
Placeholder code cannot preserve the Stack invariant or satisfy the public contract.
Prevent it: Implement the smallest complete transition and run the public tests before adding optimizations.
Avoid
def reduce_adjacent_pairs(tokens):
passUse instead
def reduce_adjacent_pairs(tokens):
stack = []
for token in tokens:
if stack and stack[-1] == token:
stack.pop()
else:
stack.append(token)
return stackWhere you will hit this: Apply One Stack Reduction(opens in a new tab)
Pushes the current token even after popping its matching neighbor, so canceled pairs remain represented.
Prevent it: Keep this invariant visible while editing: State the precise Stack invariant before coding and preserve it after every update, traversal step, or recursive return.
Avoid
def reduce_adjacent_pairs(tokens):
stack = []
for token in tokens:
if stack and stack[-1] == token:
stack.pop()
stack.append(token)
return stackUse instead
def reduce_adjacent_pairs(tokens):
stack = []
for token in tokens:
if stack and stack[-1] == token:
stack.pop()
else:
stack.append(token)
return stackWhere you will hit this: Apply One Stack Reduction(opens in a new tab)
Handle empty state, duplicate values, aliasing, and serialization boundaries explicitly in tests.
Prevent it: Account for every slice, copy, sort, membership test, and container mutation before claiming O(n).
Avoid
def reduce_adjacent_pairs(tokens):
stack = []
for token in tokens:
if stack and stack[-1] == token:
stack.pop()
stack.append(token)
return stackUse instead
def reduce_adjacent_pairs(tokens):
stack = []
for token in tokens:
if stack and stack[-1] == token:
stack.pop()
else:
stack.append(token)
return stackWhere you will hit this: Min Stack(opens in a new tab)
Official Python documentation supports language behavior. Canonical problem pages provide additional practice context.
python-docs · checked 2026-07-27