Evaluate Reverse Polish Notation - Problem
Reverse Polish Notation (RPN) is a mathematical notation where operators come after their operands, eliminating the need for parentheses. For example, the infix expression
You are given an array of strings
Supported Operations:
• Addition (
• Subtraction (
• Multiplication (
• Division (
Example:
Step by step:
3 + 4 becomes 3 4 + in RPN.You are given an array of strings
tokens that represents an arithmetic expression in Reverse Polish Notation. Your task is to evaluate this expression and return the result as an integer.Supported Operations:
• Addition (
+)• Subtraction (
-)• Multiplication (
*)• Division (
/) - always truncates toward zeroExample:
["2", "1", "+", "3", "*"] evaluates to 9Step by step:
2 1 + → 3, then 3 3 * → 9 Input & Output
example_1.py — Basic RPN Expression
$
Input:
["2", "1", "+", "3", "*"]
›
Output:
9
💡 Note:
Step-by-step: Push 2, push 1, then '+' pops 1 and 2, computes 2+1=3, pushes 3. Push 3, then '*' pops 3 and 3, computes 3*3=9, pushes 9. Final result is 9.
example_2.py — Division with Truncation
$
Input:
["4", "13", "5", "/", "+"]
›
Output:
6
💡 Note:
Step-by-step: Push 4, push 13, push 5. '/' pops 5 and 13, computes 13/5=2 (truncated), pushes 2. '+' pops 2 and 4, computes 4+2=6, pushes 6.
example_3.py — Complex Expression
$
Input:
["10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"]
›
Output:
22
💡 Note:
This complex expression evaluates through multiple stack operations: ((10 * (6 / ((9 + 3) * -11))) + 17) + 5 = 22
Visualization
Tap to expand
Understanding the Visualization
1
Initialize
Start with empty stack and first token
2
Process Numbers
Push numbers onto the stack as they appear
3
Process Operators
Pop two operands, calculate, push result
4
Continue
Repeat until all tokens are processed
5
Return Result
The final stack contains exactly one element - the answer
Key Takeaway
🎯 Key Insight: The stack's LIFO behavior perfectly matches RPN's evaluation order - most recent operands are used first!
Time & Space Complexity
Time Complexity
O(n)
Each token is processed exactly once, each stack operation is O(1)
✓ Linear Growth
Space Complexity
O(n)
Stack can grow up to the size of input in worst case (all numbers)
⚡ Linearithmic Space
Constraints
- 1 ≤ tokens.length ≤ 104
-
tokens[i] is either an operator:
"+","-","*", or"/", or an integer in the range[-200, 200] - Valid RPN expression - guaranteed to be well-formed
- Division result will always be an integer (no remainder handling needed)
- All intermediate and final results fit in a 32-bit signed integer
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code