Evaluate Reverse Polish Notation
The key idea
In postfix notation every operator acts on the two most recently produced values, so a stack is the perfect fit: push numbers, and on each operator pop the top two operands, apply it, and push the result back. The final stack holds exactly one value — the answer.
Problem
You are given an array of strings tokens that represents an arithmetic expression in Reverse Polish Notation (postfix notation).
Evaluate the expression and return an integer that represents its value.
Each tokens[i] is either an operator — "+", "-", "*", or "/" — or an integer. 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 fit in a 32-bit integer.
Constraints
1 <= tokens.length <= 10^4tokens[i]is either an operator ("+","-","*", or"/") or an integer in the range[-200, 200]- The input is always a valid arithmetic expression in Reverse Polish Notation
- The answer and all intermediate results fit in a 32-bit integer
Examples
Input: tokens = ["2","1","+","3","*"]
Output: 9
Input: tokens = ["4","13","5","/","+"]
Output: 6
Input: tokens = ["10","6","9","3","+","-11","*","/","*","17","+","5","+"]
Output: 22
Complexity
Time: O(n) Space: O(n)
See the full solution
- ✓Full worked approach
- ✓Reference code in 5 languages
- ✓Problem-solving tips
- ✓Step-by-step animated visualization
More Stack / Queue problems
- Asteroid CollisionMEDIUM
- Baseball GameEASY
- Basic CalculatorHARD
- Decode StringMEDIUM
- Longest Valid ParenthesesHARD
- Min StackMEDIUM
- Number of Recent CallsEASY
- Remove All Adjacent Duplicates In StringEASY
- Removing Stars From a StringMEDIUM
- Simplify PathMEDIUM
- Valid ParenthesesEASY