150. Evaluate Reverse Polish Notation
You are given an array of strings tokens that represents an arithmetic expression in a Reverse Polish Notation.
Evaluate the expression. 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 a reverse polish notation.
- The answer and all the intermediate calculations can be represented in a 32-bit integer.
Example 1:
Example 2:
Example 3:
- 1 <= tokens.length <= 104
- tokens[i] is either an operator: "+", "-", "*", or "/", or an integer in the range [-200, 200].
Constraints:
Notes
Intuition
Reverse Polish Notation places operators after their operands. A stack naturally handles this—operands accumulate until an operator consumes them, and intermediate results stay on the stack for future operations.
Implementation
Iterate through tokens. If it's a number, push to stack. If it's an operator, pop the top two values, apply the operation, and push the result back. The final answer is the single value remaining on the stack.
Edge-cases
Python's integer division // rounds toward negative infinity, not toward zero. Use int(b / a) for truncation toward zero. Also remember operand order matters for subtraction and division—the second popped value is the left operand (b - a, int(b / a)).
- Time: O(n) — single pass through tokens
- Space: O(n) — stack holds intermediate values