Evaluate Reverse Polish Notation - Problem
You are given an array of strings tokens that represents an arithmetic expression in Reverse Polish Notation.
Evaluate the expression and return an integer that represents the value of the expression.
Note that:
- The valid operators are
'+','-','*', and'/' - Each operand may be an integer or another expression
- The division between two integers always truncates toward zero
- There will not be any division by zero
- The input represents a valid arithmetic expression in reverse polish notation
- The answer and all intermediate calculations can be represented in a 32-bit integer
Input & Output
Example 1 — Basic RPN Expression
$
Input:
tokens = ["2","1","+","3","*"]
›
Output:
9
💡 Note:
Step by step: Push 2, push 1, encounter '+' so pop 1 and 2, compute 2+1=3, push 3. Push 3, encounter '*' so pop 3 and 3, compute 3*3=9, push 9. Result is 9.
Example 2 — Division with Truncation
$
Input:
tokens = ["4","13","5","/","+"]
›
Output:
6
💡 Note:
Push 4, push 13, push 5, encounter '/' so pop 5 and 13, compute 13/5=2 (truncated), push 2. Encounter '+' so pop 2 and 4, compute 4+2=6.
Example 3 — Negative Result
$
Input:
tokens = ["10","6","9","3","+","-11","*","/","*","17","+","5","+"]
›
Output:
22
💡 Note:
Complex expression that evaluates through multiple stack operations, handling negative numbers and multiple operators.
Constraints
- 1 ≤ tokens.length ≤ 104
- tokens[i] is either an operator: "+", "-", "*", or "/", or an integer in the range [-200, 200]
Visualization
Tap to expand
Understanding the Visualization
1
Input
Array of tokens representing RPN expression
2
Process
Use stack to evaluate: push numbers, pop and compute for operators
3
Output
Single integer result of the expression
Key Takeaway
🎯 Key Insight: RPN eliminates the need for parentheses by using postfix notation where operators follow their operands
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code