Stacks and bracket matching
A stack removes the most recently added item first. This last-in, first-out rule is abbreviated LIFO. Use a stack when the next item to resolve is the latest unfinished item, such as a bracket, an undo action, or a recursive call.
Python’s list supplies the required operations at its right end.
Read arrays and Python lists for its storage model.
The bracket examples below use invented strings.
Push, peek, and pop
Section titled “Push, peek, and pop”append pushes an item, stack[-1] peeks at the top, and pop removes the top.
Check that the stack is nonempty before a peek or pop.
Both operations raise IndexError on an empty list.
stack: list[str] = []stack.append("draft")print("Push draft:", stack)stack.append("edit")print("Push edit:", stack)print("Peek:", stack[-1])print("Pop:", stack.pop())print("Remaining:", stack)Push draft: ['draft']Push edit: ['draft', 'edit']Peek: editPop: editRemaining: ['draft']The rightmost displayed item is the top.
Push and pop take O(1) amortized time with a Python list, while a peek takes O(1) time.
An individual resize can take O(n), where n is the current stack size.
Check bracket nesting
Section titled “Check bracket nesting”A miniature expression language contains only the six bracket characters ()[]{}.
Return whether every closing bracket matches the latest unmatched opening bracket.
An empty string is valid.
Inputs containing another character raise ValueError.
Store opening brackets in a stack. Before each character, the stack contains exactly the unmatched opening brackets in their original order. A closing bracket must match the top, because a later opening bracket must close before an earlier one.
def brackets_match(text: str) -> bool: """Check whether a string contains correctly nested brackets.
Args: text: A string containing only parentheses, brackets, or braces.
Returns: Whether all opening and closing brackets match in nesting order.
Raises: ValueError: If text contains a character other than a bracket. """ if any(character not in "()[]{}" for character in text): raise ValueError("Only bracket characters are supported.") opening_for = {")": "(", "]": "[", "}": "{"} stack: list[str] = [] for character in text: if character in "([{": stack.append(character) elif not stack or stack.pop() != opening_for[character]: return False return not stack
expression = "([{}])"stack = []opening_for = {")": "(", "]": "[", "}": "{"}for character in expression: if character in "([{": stack.append(character) action = "push" else: matched = bool(stack) and stack.pop() == opening_for[character] assert matched action = "match and pop" print("Read:", character, "Action:", action, "Stack:", stack)print("Valid:", brackets_match(expression))Read: ( Action: push Stack: ['(']Read: [ Action: push Stack: ['(', '[']Read: { Action: push Stack: ['(', '[', '{']Read: } Action: match and pop Stack: ['(', '[']Read: ] Action: match and pop Stack: ['(']Read: ) Action: match and pop Stack: []Valid: TrueThe empty final stack proves that no opening bracket remains unmatched.
Equal counts alone are insufficient; ([)] has balanced counts but incorrect nesting.
A closing bracket with an empty stack also fails immediately.
Explain the cost
Section titled “Explain the cost”For n characters, the validation scan takes O(n) time.
The matching scan pushes or pops each bracket at most once, so total time is O(n).
An input containing only opening brackets stores all n characters, giving O(n) worst-case auxiliary space.
More precisely, the stack holds at most the maximum unmatched nesting depth.
The trace prints the stack after each character.
Its display work can take O(n²), but the brackets_match function does not perform that display work.
for text, expected in [ ("", True), ("()[]{}", True), ("([{}])", True), ("([)]", False), (")", False), ("((", False),]: assert brackets_match(text) == expected print(repr(text), brackets_match(text))try: brackets_match("(a)")except ValueError as error: print(type(error).__name__, str(error))'' True'()[]{}' True'([{}])' True'([)]' False')' False'((' FalseValueError Only bracket characters are supported.Practice
Section titled “Practice”- Solve Valid Parentheses with the unmatched-opening invariant. Test a wrong bracket type as well as an unmatched bracket.
- Solve Daily Temperatures with a stack of unresolved indices. Explain why an index leaves the stack at most once.
Continue with monotonic stacks for a complete next-greater-value example and its amortized analysis.
Download the Python source to run the complete example locally.
Further reading
Section titled “Further reading”The Python stack tutorial describes the list operations used for LIFO access. It connects the abstract structure to Python syntax.
Open Data Structures on array stacks explains array-based stack operations and resizing. Its amortized analysis clarifies why occasional copies do not make a sequence of pushes quadratic.