Evaluate Reverse Polish Notation

Free with account Updated Nov 19, 2026 · 5 min read
On this page

    Problem statement

    Evaluate an arithmetic expression written in Reverse Polish Notation (postfix) and return its integer value. The input is a list of tokens: integers (possibly negative) and the operators +, -, *, /. Each operator applies to the two values produced just before it. Division truncates toward zero. The expression is always valid and never divides by zero.

    A short stack question that checks whether you know why postfix needs no parentheses, and whether you get the operand order and integer division right. Original problem: LeetCode 150.

    Example

    Each operator comes right after the two values it combines, so 3 4 + 2 * 7 − means (3 + 4) × 2 − 7.
    Each operator comes right after the two values it combines, so 3 4 + 2 * 7 − means (3 + 4) × 2 − 7.
    Input:  ["3", "4", "+", "2", "*", "7", "-"]
    Output: 7                                     # (3 + 4) * 2 - 7
    Input:  ["15", "7", "1", "1", "+", "-", "/", "3", "*"]   ->  9     # 15 / (7 - (1 + 1)) * 3
    Input:  ["7", "-2", "/"]                                 ->  -3    # truncate toward zero

    Constraints (assumed)

    • 1 ≤ number of tokens ≤ 10⁴; every intermediate value fits in 32 bits.

    What this question tests

    • Recognizing that postfix evaluation is a stack problem.
    • Popping operands in the right order for - and /.
    • Language details: truncating division and parsing negative numbers.

    Questions to ask first

    1. How does division round? (Here: toward zero, so 7 / −2 = −3.)
    2. Can numbers be negative? (Here: yes; "-2" is a number, "-" is an operator.)
    3. Is the input always valid? (Here: yes. Validation is a follow-up.)
    4. Which operators? (Here: the four basic ones.)