Mathwords logoMathwords

Reverse Polish Notation — Definition, Formula & Examples

Reverse Polish Notation (RPN) is a way of writing mathematical expressions where every operator comes after its operands instead of between them. For example, instead of writing 3+43 + 4, you write 3 4 +3 \ 4 \ +.

Reverse Polish Notation, also called postfix notation, is a mathematical notation in which each operator immediately follows all of its operands. An expression in RPN is evaluated left to right using a stack: operands are pushed onto the stack, and when an operator is encountered, the required number of operands are popped, the operation is performed, and the result is pushed back. This notation is unambiguous without parentheses or operator-precedence rules.

How It Works

To evaluate an RPN expression, read it from left to right. When you see a number, place it on an imaginary stack. When you see an operator (++, -, ×\times, ÷\div), take the top two numbers off the stack, apply the operator, and put the result back. The second number you removed is the left operand, and the first is the right operand. When you reach the end, the single number left on the stack is your answer.

Worked Example

Problem: Evaluate the RPN expression: 5 1 2 + 4 × + 3 −
Step 1: Push 5, 1, and 2 onto the stack. Encounter +, so pop 1 and 2, compute their sum, and push the result.
1+2=3Stack: [5,3]1 + 2 = 3 \quad \text{Stack: } [5, 3]
Step 2: Encounter 4, push it. Then encounter ×, so pop 3 and 4, multiply, and push the result.
3×4=12Stack: [5,12]3 \times 4 = 12 \quad \text{Stack: } [5, 12]
Step 3: Encounter +, so pop 5 and 12, add them, and push the result.
5+12=17Stack: [17]5 + 12 = 17 \quad \text{Stack: } [17]
Step 4: Encounter 3, push it. Then encounter −, so pop 17 and 3, subtract, and push the result.
173=14Stack: [14]17 - 3 = 14 \quad \text{Stack: } [14]
Answer: The RPN expression evaluates to 14. This is equivalent to the infix expression (5+((1+2)×4))3(5 + ((1 + 2) \times 4)) - 3.

Why It Matters

RPN is used internally by many calculators (especially HP scientific calculators) and forms the basis of stack-based computing. Understanding it deepens your grasp of how computers parse and evaluate algebraic expressions, which is directly relevant in computer science courses and compiler design.

Common Mistakes

Mistake: Reversing the operand order for subtraction and division.
Correction: In the expression 7 2 7 \ 2 \ -, the 7 is the left operand and 2 is the right, giving 72=57 - 2 = 5, not 272 - 7. The second-to-top stack element is always the left operand.