Evaluate Reverse Polish Notation
Master this topic with zero to advance depth.
Evaluate Reverse Polish Notation
Evaluate the value of an arithmetic expression in Reverse Polish Notation. Valid operators are +, -, *, and /.
Visual Representation
Tokens: ["2", "1", "+", "3", "*"]
1. Token "2": Push. Stack: [2]
2. Token "1": Push. Stack: [2, 1]
3. Token "+": Pop 1, Pop 2. Res = 2 + 1 = 3. Push. Stack: [3]
4. Token "3": Push. Stack: [3, 3]
5. Token "*": Pop 3, Pop 3. Res = 3 * 3 = 9. Push. Stack: [9]
Result: 9Examples
((2 + 1) * 3) = 9
Level I: Brute Force (Recursive Evaluation)
Intuition
Without knowing the stack trick, one naive approach is to scan the token list for an operator, evaluate the two preceding operands, replace those three tokens with the result, and repeat until one token remains. This is simpler to reason about but requires repeated passes over the list.
Level III: Optimal (Stack Evaluation)
Intuition
Use a stack to store operands. When an operator is encountered, pop the top two operands, apply the operator, and push the result back. This naturally handles the postfix order without parentheses.
Detailed Dry Run
| Token | Action | Stack Status | Calculated |
|---|---|---|---|
| "2" | Push | [2] | - |
| "1" | Push | [2, 1] | - |
| "+" | Pop, Pop, Add | [3] | 2 + 1 = 3 |
| "3" | Push | [3, 3] | - |
| "*" | Pop, Pop, Mul | [9] | 3 * 3 = 9 |
⚠️ Common Pitfalls & Tips
Be mindful of integer division in Python (int(a/b)) and JavaScript (Math.trunc(a/b)), as they must truncate toward zero.
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.