Skip to contentKEEP THE CRAFTTHE SANCTUARY

Stack

Use a stack when the next input can resolve only the most recent unfinished item. Represent that boundary with the right end of a Python list, then prove nesting or cancellation by the meaning of the stack after every token.

3 practice exercises14 interview problems

Recognize it when Nested openings must close in reverse arrival order.

Checking your account…

Stack Code Labs

Mental Model

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.

Python List as a Stack

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.

Match Nested State

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.

Match Nested Delimiters

Reference
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 stack
Practice

Implement is_balanced(text) for (), [], and {}. Ignore non-delimiter characters and require every closer to match the latest unmatched opener.

Public tests

  • Verify LIFO delimiter matching

Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor

Match Nested Delimiters

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 stack

Reduce with the Stack Top

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.

Reduce Adjacent Equal Pairs

Reference
def reduce_adjacent_pairs(tokens):
    stack = []
    for token in tokens:
        if stack and stack[-1] == token:
            stack.pop()
        else:
            stack.append(token)
    return stack
Practice

Implement reduce_adjacent_pairs(tokens). Cancel the current token with an equal stack top; otherwise push it, then return the reduced sequence.

Public tests

  • Verify cascading top reductions

Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor

Reduce Adjacent Equal Pairs

def reduce_adjacent_pairs(tokens):
    stack = []
    for token in tokens:
        if stack and stack[-1] == token:
            stack.pop()
        else:
            stack.append(token)
    return stack

Trace Cancellation Exposing the Previous Top

The reduction Lab processes a, b, b, a, c in that order. The second b removes the current top, exposing a; the next a can then remove that older unresolved token. Nothing requires rescanning the earlier prefix.

print(reduce_adjacent_pairs(['a', 'b', 'b', 'a', 'c'])) followed by print(reduce_adjacent_pairs([]))

Step Executed statement State Why
1 stack.append(token) token = 'a'; stack = ['a'] Empty state has no partner, so a remains unresolved.
2 stack.append(token) token = 'b'; stack = ['a', 'b'] Different top and token cannot cancel.
3 stack.pop() token = 'b'; stack = ['a'] Equal adjacent b tokens disappear, exposing the earlier a.
4 stack.pop() token = 'a'; stack = [] The newly exposed a is now the current token’s neighbor.
5 stack.append(token); return stack token = 'c'; result = ['c'] The final unmatched token is the reduced result.
Print Output
1 ['c']
2 []

Each input contributes either one push or one pop. The cascade comes from exposing the old top, not from repeating scans. This aggregate accounting explains linear time even when several earlier tokens disappear across later inputs.

Choose Stack or Recursion

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.

Stack Top and Nesting Mistakes

  • Peeking or popping before checking emptiness turns a valid unmatched closer into IndexError.
  • Searching the entire stack ignores nesting and adds unnecessary linear work per input.
  • Copying a full path into every traversal frame can produce quadratic memory use.
  • Pushing children in natural order visits them in reverse because the last child is popped first.

Explain It in an Interview

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.

Template To Memorize

Learn this shape by heart; most problems in this family change only one or two lines of it.

Stack for matching pairs

Open pushes; close must match the top; end empty.

Items must be closed in reverse order of opening, or you evaluate something that needs the most recent items first.

Trigger words

  • valid parentheses
  • matching brackets
  • reverse polish
  • nested
  • undo
  • min stack
def is_valid(s):
    pairs = {')': '(', ']': '[', '}': '{'}
    stack = []
    for char in s:
        if char in pairs:                        # a closing bracket
            if not stack or stack[-1] != pairs[char]:
                return False
            stack.pop()
        else:                                    # an opening bracket
            stack.append(char)
    return not stack                             # nothing left open

Spot it when

  • Brackets, nested structures.
  • Reverse Polish notation, undo-like processing.

Remember

  • The top of the stack is always the most recent unfinished item.
  • Check for an empty stack before reading stack[-1].

How problems bend it

  • Evaluate Reverse Polish Notation: Push numbers; on an operator pop two, apply it, push the result.
  • Min stack: Push (value, minimum so far) pairs so the minimum survives pops.

Python Version Note

Complexity & Invariants

Interview bounds depend on the stated representation, input model, and real Python operations.

OperationAverageWorstInterview note
Right-end pushO(1) amortizedO(n)List growth may resize storage; n is maximum pending stack length.
Delimiter scan or pair reductionO(n)O(n)Every input token is pushed at most once and popped at most once; no whole-stack search or copy is performed.

Space

O(n) for right-end push; O(n) for delimiter scan or pair reduction.

Assumptions

  • List growth may resize storage; n is maximum pending stack length.
  • Every input token is pushed at most once and popped at most once; no whole-stack search or copy is performed.

Invariants Worth Saying Aloud

  1. The top is the most recent unresolved input item.
  2. For delimiter matching, the stack contains unmatched openers in nesting order.
  3. For pair reduction, the stack is the reduced processed prefix with no adjacent equal pair.

When To Use Or Avoid Stack

Use It When

  • Store unmatched delimiters or a fully reduced processed prefix.
  • Use explicit frames when recursive depth or visit order needs direct control.

Choose Another Tool When

  • Use a queue when oldest pending work must leave first.
  • Do not search deeper in the stack to excuse an invalid top match.

Common Pitfalls

These are the mistakes most likely to survive a happy-path example and fail a boundary case.

Peeking before checking empty state

An unmatched closer or the first reduction token can encounter an empty stack. Indexed access then raises IndexError before the algorithm can reject or push it.

Prevent it: Use a short-circuit emptiness guard before inspecting the top.

Avoid

matches = stack[-1] == token

Use instead

matches = bool(stack) and stack[-1] == token

Accepting an opener deeper than the top

A compatible opener somewhere in the stack does not validate nesting. With '(' below '[', ')' would cross the unfinished bracket.

Prevent it: Compare the closer's expected opener to the top only.

Avoid

matches = matching[closer] in stack

Use instead

matches = bool(stack) and stack[-1] == matching[closer]

Reinserting a token after its pair was canceled

An unconditional append leaves one canceled token in the state. Cancellation and pushing are mutually exclusive transitions.

Prevent it: Put the push in the else branch of the top-match test.

Avoid

if stack and stack[-1] == token:
    stack.pop()
stack.append(token)

Use instead

if stack and stack[-1] == token:
    stack.pop()
else:
    stack.append(token)

Reviewed References

Official Python documentation supports language behavior. Canonical problem pages provide additional practice context.