Topic 04 of 14

Stack Patterns

3 patterns and 15 practice problems, each with a recall tip, a diagram, the theory and a Python template.

01

Stack - Matching Brackets / Parentheses

5 practice problems

Theory

  • Push opening brackets onto the stack. On closing bracket, pop and check if it matches.
  • If the stack is empty when popping, or non-empty at the end — invalid.
  • Extend to multi-character tokens (e.g., HTML tags) by storing full tokens on the stack.
  • Time: O(n), Space: O(n) worst case.

Code template

python
def is_valid(s):
    stack = []
    pairs = {')': '(', ']': '[', '}': '{'}
    for ch in s:
        if ch in pairs:
            if not stack or stack[-1] != pairs[ch]:
                return False
            stack.pop()
        else:
            stack.append(ch)
    return len(stack) == 0
02

Stack - Monotonic Stack (Next Greater / Smaller)

5 practice problems

Theory

  • Maintain a stack in increasing (or decreasing) order.
  • For "next greater element": pop elements smaller than current, they found their answer.
  • For "next smaller element": pop elements greater than current.
  • Time: O(n) — each element is pushed and popped at most once.

Code template

python
def next_greater_element(nums):
    n = len(nums)
    result = [-1] * n
    stack = []  # stores indices
    for i in range(n):
        while stack and nums[i] > nums[stack[-1]]:
            idx = stack.pop()
            result[idx] = nums[i]
        stack.append(i)
    return result

Practice problems · 5

03

Stack - Expression Evaluation

5 practice problems

Theory

  • Use a stack of numbers. When you see an operator, pop operands, compute, push result.
  • For infix: convert to postfix first, or handle precedence with two stacks.
  • Reverse Polish Notation (postfix) is naturally stack-friendly.
  • Handle unary minus and multi-digit numbers carefully during parsing.

Code template

python
def eval_rpn(tokens):
    stack = []
    ops = {'+': lambda a, b: a + b,
           '-': lambda a, b: a - b,
           '*': lambda a, b: a * b,
           '/': lambda a, b: int(a / b)}
    for token in tokens:
        if token in ops:
            b, a = stack.pop(), stack.pop()
            stack.append(ops[token](a, b))
        else:
            stack.append(int(token))
    return stack[0]

Practice problems · 5

Spotted a mistake on this page?

Wrong formula, broken animation or confusing wording. Tell us and we will fix it.