Evaluate Reverse Polish Notation
Expert Answer & Key Takeaways
A complete guide to understanding and implementing Stack.
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
Input: tokens = ["2","1","+","3","*"]
Output: 9
((2 + 1) * 3) = 9
Approach 1
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.
⏱ O(N^2) because for each of the N tokens that is an operator, we scan back to find the two operands.💾 O(N) for the mutable token list copy.
Approach 2
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.
⏱ O(N)💾 O(N)
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.Course4All Technical Board
Verified ExpertSenior Software Engineers & Algorithmic Experts
Our DSA content is authored and reviewed by engineers from top tech firms to ensure optimal time and space complexity analysis.
Pattern: 2026 Ready
Updated: Weekly
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.