Evaluate a Simple Postfix (RPN) Arithmetic Expression
Stacks & QueuesAuto-graded · 17 test casesLast updated
Tests whether a candidate can use a stack to correctly evaluate a postfix arithmetic expression involving integers and the four basic operators.
Postfix Expression Evaluator
A postfix (Reverse Polish Notation) expression is a sequence of tokens where every operator appears after its two operands, eliminating the need for parentheses or precedence rules.
For example, the infix expression (3 + 4) * 2 is written in postfix as 3 4 + 2 *.
You are given a list of tokens that form a valid postfix expression. Each token is either:
- An integer (may be negative), represented as a string such as
"3","-7","0", or - One of the four operators:
"+","-","*","/".
Evaluate the expression and return the integer result.
Division rule
Division is integer division that truncates toward zero (i.e., Python's int(a / b), not a // b). Examples: 7 / 2 = 3, -7 / 2 = -3, 7 / -2 = -3.
How evaluation works
Use a stack:
- For each token left-to-right:
- If it is a number, push it onto the stack.
- If it is an operator, pop the top two values. The second-from-top is the left operand and the top is the right operand. Apply the operator and push the result.
- After processing all tokens, the stack contains exactly one value — the result.
You may assume the input is always a valid postfix expression with at least one token, that division by zero never occurs, and that all intermediate and final results fit in a 32-bit signed integer.
Constraints
1 ≤ len(tokens) ≤ 200- Each numeric token represents an integer in the range
[-1000, 1000]. - Operators are drawn from
{"+", "-", "*", "/"}. - The expression is guaranteed to be valid (never leaves the stack in an inconsistent state).
- Integer division truncates toward zero.
Examples
Example 1
Input: evaluate_postfix(['3', '4', '+', '2', '*'])
Output: 14
Example 2
Input: evaluate_postfix(['5', '1', '2', '+', '4', '*', '+', '3', '-'])
Output: 14
Example 3
Input: evaluate_postfix(['-7', '2', '/'])
Output: -3
Hints
Hint 1
Push numbers onto a stack as you scan left to right; when you see an operator, pop two values and push the result back.
Hint 2
Be careful about operand order: the value popped first is the RIGHT operand, and the value popped second is the LEFT operand.
Hint 3
Use int(a / b) rather than a // b to get truncation toward zero for negative numbers (e.g., int(-7 / 2) == -3, but -7 // 2 == -4 in Python).
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Core idea
A stack is the natural data structure for postfix evaluation because the nesting of operations is encoded by token order — operands always appear before the operator that consumes them.
Algorithm:
- Initialise an empty stack.
- Scan tokens left to right.
- Number token: convert to
intand push. - Operator token: pop
right, then popleft, computeleft OP right, push result.
- Number token: convert to
- Return the single remaining element.
Why it is correct
Postfix notation guarantees that when we reach an operator, its two operands are already on top of the stack in the correct order (left operand deeper, right operand on top). The stack invariant is maintained throughout, and a valid expression always leaves exactly one value.
Division toward zero
Python's // operator floors toward negative infinity (-7 // 2 == -4), but the problem requires truncation toward zero (-7 / 2 → -3). Using int(left / right) (float division then truncation) gives the correct result for all cases within the given integer range.
Complexity
- Time: O(n) — each token is processed once, and each stack operation is O(1).
- Space: O(n) — the stack holds at most ⌈n/2⌉ values at any time (every other token is an operator in the densest case).
from typing import List
def evaluate_postfix(tokens: List[str]) -> int:
stack = []
operators = {'+', '-', '*', '/'}
for token in tokens:
if token in operators:
right = stack.pop()
left = stack.pop()
if token == '+':
stack.append(left + right)
elif token == '-':
stack.append(left - right)
elif token == '*':
stack.append(left * right)
elif token == '/':
# Truncate toward zero
stack.append(int(left / right))
else:
stack.append(int(token))
return stack[0]