← All Foundations

Stacks & Queues

Foundation drill for this topic

Drill #19 — Evaluate postfix expression

Easy Operand Stack

In plain English: Calculate the result of a math expression written in postfix notation like '2 1 + 3 *'.

Postfix notation eliminates the need for parentheses and precedence — operands are always ready on the stack when an operator appears.

Prompt

Evaluate a postfix (reverse Polish notation) expression.

Try to write it from scratch before scrolling down.

Solution

def eval_postfix(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 t in tokens:
        if t in ops:
            b, a = stack.pop(), stack.pop()  # pop order matters: b first, then a
            stack.append(ops[t](a, b))
        else:
            stack.append(int(t))
    return stack[0]

# Test: eval_postfix(["2","1","+","3","*"]) == 9
O(n) time · O(n) space

Related Micro Drills

Quick recall drills to reinforce this pattern.

37 Evaluate postfix token Stack Discipline 15s

Stack-based expression evaluation is the foundation for calculator and RPN problems.

for tok in tokens:
    if tok.lstrip('-').isdigit():
        stack.append(int(tok))
    else:
        b, a = stack.pop(), stack.pop()
        if tok == '+': stack.append(a + b)
        elif tok == '-': stack.append(a - b)
        elif tok == '*': stack.append(a * b)
        elif tok == '/': stack.append(int(a / b))
272 Evaluate Reverse Polish Notation Stack Discipline 15s

RPN evaluation: numbers push, operators pop two and push result. Note: pop order is b, a (right operand first).

stack = []
for tok in tokens:
    if tok in '+-*/':
        b, a = stack.pop(), stack.pop()
        if tok == '+': stack.append(a + b)
        elif tok == '-': stack.append(a - b)
        elif tok == '*': stack.append(a * b)
        else: stack.append(int(a / b))
    else:
        stack.append(int(tok))
34 Push and pop Stack Discipline 5s

Stack push/pop is the foundation for all LIFO operations: DFS, undo, and expression parsing.

stack = []
stack.append(x)
stack.pop()
See all drills in Stacks & Queues →