Skip to content

Postfix Expression Evaluator

1/19

How do you evaluate a postfix expression?

To evaluate a postfix (Reverse Polish) expression such as 5 1 2 + 4 * + 3 -, scan it left to right with a stack: push every number, and for every operator pop two values — the first pop is the right operand — apply the operator and push the result. A valid expression leaves exactly one value on the stack, the answer (14 here), after O(n) work.

How it works

  1. Split the expression into tokens and start with an empty stack.
  2. Number: push it.
  3. Operator: pop b (the right operand, pushed last), then pop a (the left operand), compute a op b and push the result. With fewer than two values on the stack the expression is invalid.
  4. At the end exactly one value must remain: that is the result. More than one means there were too few operators.

Worked example: 5 1 2 + 4 * + 3 -

  • 5, 1, 2 → push each. Stack: 5 1 2
  • + → b = 2, a = 1, 1 + 2 = 3. Stack: 5 3
  • 4 → push. Stack: 5 3 4
  • * → b = 4, a = 3, 3 × 4 = 12. Stack: 5 12
  • + → b = 12, a = 5, 5 + 12 = 17. Stack: 17
  • 3 → push. Stack: 17 3
  • - → b = 3, a = 17, 17 − 3 = 14. Stack: 14

One value is left, so the expression equals 14. In infix it reads 5 + (1 + 2) × 4 - 3. This example is preloaded in the visualizer above, which shows the two operands lifting off the stack for every operator.

Operand order matters

Because the stack returns the most recent value first, the first pop is the right-hand operand. For + and * the order makes no difference, but for -, /, % and ^ it does:

  • 10 4 - is 10 − 4 = 6, not −6.
  • 10 4 - 3 / is (10 − 4) / 3 = 2.
  • 2 3 2 ^ ^ is 2^(3^2) = 512, while 2 3 ^ 2 ^ is (2^3)^2 = 64 — postfix spells the grouping out explicitly.

Detecting invalid expressions

  • Not enough operands — 1 +: the operator finds fewer than two values on the stack (too many operators, or one too early).
  • Too many operands — 1 2 3 +: two values, 1 and 5, remain at the end (too few operators).
  • Division by zero — 8 0 /: the expression has no value.
  • Unknown tokens — a variable such as x has no value to push.

A quick sanity check for binary operators: a valid postfix expression has exactly one more operand than operators, and while scanning from the left the operands seen always outnumber the operators seen.

Why postfix? Where it is used

Postfix needs no parentheses and no precedence rules, so a machine can evaluate it in one pass with one stack. That is exactly how stack machines work: Java bytecode, .NET CIL, WebAssembly, CPython bytecode, PostScript and Forth all push operands and let instructions pop them.

HP calculators made Reverse Polish notation famous, and compilers turn infix source into an expression tree or postfix-like code before generating instructions. To evaluate an ordinary infix expression yourself, convert it with the shunting-yard algorithm first, then run this evaluator.

Common mistakes

  • Swapping the operands — computing b - a instead of a - b.
  • Integer-division surprises: in Python 7 / 2 is 3.5. LeetCode 150 wants truncation toward zero, which is int(a / b), not a // b (that floors: -7 // 2 == -4).
  • Splitting multi-digit numbers into characters — separate the tokens with spaces.
  • Confusing a negative number such as -3 with the operator - followed by 3: decide how negatives are written and tokenize accordingly.
  • Not checking that exactly one value remains at the end.

Prefix evaluation and interview variations

Prefix (Polish) expressions are evaluated the same way but scanned right to left, and then the first value popped is the left operand. - + 5 * + 1 2 4 3 also gives 14.

  • Evaluate Reverse Polish Notation (LeetCode 150): this exact algorithm with integer division that truncates toward zero.
  • Postfix to infix: push strings and build "(a op b)" for every operator.
  • Expression trees: push leaf nodes and let each operator pop two subtrees.
  • Basic Calculator: convert infix to postfix and evaluate it, or merge both passes with two stacks.

Time and space complexity

CaseTimeSpaceWhy
EvaluationO(n)O(n)One pass; each token does O(1) stack work. Worst case, all the numbers come first.
Validity count (binary operators)O(n)O(1)Track operands minus operators: it must stay ≥ 1 and end at exactly 1.

Postfix Evaluation in Python

import math

APPLY = {
    "+": lambda a, b: a + b,
    "-": lambda a, b: a - b,
    "*": lambda a, b: a * b,
    "/": lambda a, b: a / b,
    "%": math.fmod,  # sign of a, like C++ / Java / JS
    "^": math.pow,
}


def evaluate(tokens):
    """tokens like ["5", "1", "2", "+", "4", "*", "+", "3", "-"]."""
    stack = []
    for t in tokens:
        if t not in APPLY:            # t is a number
            stack.append(float(t))
        else:                         # t is an operator
            if len(stack) < 2:
                raise ValueError("missing operand for " + t)
            b = stack.pop()           # right operand (pushed last)
            a = stack.pop()           # left operand
            stack.append(APPLY[t](a, b))
    result = stack.pop()
    if stack:
        raise ValueError("too many operands")  # the stack must now be empty
    return result


# evaluate("5 1 2 + 4 * + 3 -".split())  -> 14.0

The visualizer above shows the same code in Python, C++, Java and JavaScript.

Frequently asked questions

What is the value of the postfix expression 5 1 2 + 4 * + 3 -?

14. The steps are 1 + 2 = 3, 3 × 4 = 12, 5 + 12 = 17 and 17 − 3 = 14.

Which data structure is used to evaluate a postfix expression?

A stack. Operands wait on it until an operator pops the two most recent ones and pushes the result.

Which operand is popped first in postfix evaluation?

The right operand. For a b - the stack pops b first, then a, and computes a - b.

What is the time complexity of postfix evaluation?

O(n) time and O(n) space for n tokens: each token is either one push, or two pops and one push, all O(1).

What is Reverse Polish notation?

Another name for postfix notation, where every operator follows its operands, e.g. 3 4 + for 3 + 4. It needs no parentheses and was popularized by HP calculators.

What happens if a postfix expression is invalid?

If an operator finds fewer than two values on the stack there are too many operators; if more than one value remains at the end there are too few. Either way the expression has no single value.

Keep learning

Last updated