150. Evaluate Reverse Polish Notation ๐ง ๐ป
Last updated
Was this helpful?
Last updated
Was this helpful?
Difficulty: Medium
- Tags: Stack
, Math
Given an array of strings tokens
representing an arithmetic expression in Reverse Polish Notation (RPN), evaluate the expression and return the result as an integer.
Rules:
Valid operators: '+'
, '-'
, '*'
, and '/'
.
Each operand is either an integer or another RPN expression.
Division between two integers truncates towards zero.
No division by zero occurs.
The input always represents a valid RPN expression.
Results and intermediate calculations fit in a 32-bit integer.
๐น Example 1:
Input:
Output:
Explanation: ((2 + 1) * 3) = 9
๐น Example 2:
Input:
Output:
Explanation: (4 + (13 / 5)) = 6
๐น Example 3:
Input:
Output:
Explanation:
1 <= tokens.length <= 10^4
Each tokens[i]
is:
An operator: '+'
, '-'
, '*'
, '/''
, or
An integer in the range [-200, 200]
.
To evaluate an RPN expression efficiently, we use a stack:
Traverse the tokens one by one:
If the token is a number, push it onto the stack.
If the token is an operator, pop the top two numbers from the stack, perform the operation, and push the result back onto the stack.
At the end, the stack will contain a single number, which is the result.
Stack Usage:
Push operands onto the stack.
For operators, pop the top two elements, compute the result, and push the result back onto the stack.
Operator Handling:
Each operator performs its operation (+
, -
, *
, /
) on the last two numbers popped from the stack.
Edge Cases:
Division truncates towards zero (handled by Javaโs /
operator for integers).
O(n): We process each token once.
O(n): Stack space for storing numbers during computation.
You can find the full solution .