150. Evaluate Reverse Polish Notation ๐ง ๐ป
Difficulty: Medium
- Tags: Stack
, Math
Problem Statement ๐
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.
Examples ๐
๐น Example 1:
Input:
Output:
Explanation: ((2 + 1) * 3) = 9
๐น Example 2:
Input:
Output:
Explanation: (4 + (13 / 5)) = 6
๐น Example 3:
Input:
Output:
Explanation:
Constraints โ๏ธ
1 <= tokens.length <= 10^4
Each
tokens[i]
is:An operator:
'+'
,'-'
,'*'
,'/''
, orAn integer in the range
[-200, 200]
.
Solution ๐ก
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.
Java Solution
Explanation of the Solution
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).
Time Complexity โณ
O(n): We process each token once.
Space Complexity ๐พ
O(n): Stack space for storing numbers during computation.
You can find the full solution here.
Last updated