KatInterview

Evaluate a Simple Postfix (RPN) Arithmetic Expression

Stacks & QueuesAuto-graded · 17 test cases
EasyAuto-gradedStacks & Queuesstacksexpression evaluationsimulation

Last 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:

  1. 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.
  2. 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).