Evaluate Reverse Polish Notation Solution
Evaluate an arithmetic expression in Reverse Polish Notation (postfix). Valid operators are +, -, *, /.
Problem Statement
You are given an array of strings tokens representing an arithmetic expression in Reverse Polish Notation. Evaluate the expression and return the result as an integer. Division truncates toward zero. The input is always a valid RPN expression.
Why No Brute Force?
RPN was invented for stack-based evaluation. There's no simpler approach โ the stack solution is both the natural and optimal way to evaluate postfix expressions. Without a stack, you'd need to recursively reconstruct the expression tree, which is more complex, not simpler.
- RPN (postfix notation) eliminates the need for parentheses and operator precedence rules.
- The stack processes it in a single left-to-right pass.
- This is exactly how calculators and many programming language VMs (like the JVM bytecode interpreter) evaluate expressions internally.
Stack Evaluation โ O(n)
Scan tokens left to right. If it's a number, push onto stack. If it's an operator, pop two operands, apply the operator, and push the result back. The final answer is the one remaining element on the stack.
- Step 1: Create an empty stack.
- Step 2: For each token: if it's a number, push it.
- Step 3: If it's an operator, pop
b(top) thena(second). Computea op b. Push result. - Step 4: Return the single element remaining on the stack.
- Pop
bfirst, thena. The operation isa op b, notb op a. - For subtraction and division, order changes the result:
"4 2 -"= 4 โ 2 = 2, not 2 โ 4 = โ2.
Visual Walkthrough
Trace through ["2", "1", "+", "3", "*"]:
Code โ Java & Python
Complexity Analysis
| Approach | Time | Space | Trade-off |
|---|---|---|---|
| Stack โ only approach | O(n) | O(n) | Each token processed once. Stack holds at most (n+1)/2 numbers. |
Edge Cases & Pitfalls
| Case | Input | Why It Matters |
|---|---|---|
| Single number | ["42"] | No operators โ push 42, return 42. |
| Negative numbers | ["-1", "2", "+"] | Negative tokens like "-1" must be parsed, not confused with "-" operator. |
| Division truncation | ["7", "-2", "/"] | 7 / -2 = -3.5 โ truncate toward zero = -3 (not -4). |
| Subtraction order | ["4", "2", "-"] | Pop b=2, a=4. Result = 4-2=2. Swapping gives wrong answer. |
// for integer division. In Python, -7 // 2 = -4 (floor division), but the problem wants truncation toward zero: -7 / 2 = -3. Use int(a / b) instead of a // b to truncate correctly for negative results.