Evaluate Reverse Polish Notation
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.
- 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:
Input: tokens = ["2","1","+","3","*"]
Output: 9
Explanation: ((2 + 1) * 3) = 9
Example 2:
Input: tokens = ["4","13","5","/","+"]
Output: 6
Explanation: (4 + (13 / 5)) = 6
Example 3:
Input: tokens = ["10","6","9","3","+","-11","*","/","*","17","+","5","+"]
Output: 22
Explanation: ((10 * (6 / ((9 + 3) * -11))) + 17) + 5
= ((10 * (6 / (12 * -11))) + 17) + 5
= ((10 * (6 / -132)) + 17) + 5
= ((10 * 0) + 17) + 5
= (0 + 17) + 5
= 17 + 5
= 22
Constraints:
1 <= tokens.length <= 10^4
tokens[i]
is either an operator:"+"
,"-"
,"*"
, or"/"
, or an integer in the range[-200, 200]
.
Try this Problem on your own or check similar problems:
Solution:
- Java
- JavaScript
- Python
- C++
public int evalRPN(String[] tokens) {
Stack<Integer> s = new Stack<>();
for(String token: tokens){
if(token.equals("+")){
s.push(s.pop() + s.pop());
}else if(token.equals("-")){
int secondOperand = s.pop();
int firstOperand = s.pop();
s.push(firstOperand - secondOperand);
}else if(token.equals("*")){
s.push(s.pop() * s.pop());
}else if(token.equals("/")){
int secondOperand = s.pop();
int firstOperand = s.pop();
s.push(firstOperand / secondOperand);
}else{
s.push(Integer.parseInt(token));
}
}
return s.pop();
}
/**
* @param {string[]} tokens
* @return {number}
*/
var evalRPN = function (tokens) {
const stack = [];
for (let token of tokens) {
if (token === "+") {
stack.push(stack.pop() + stack.pop());
} else if (token === "-") {
const secondOperand = stack.pop();
const firstOperand = stack.pop();
stack.push(firstOperand - secondOperand);
} else if (token === "*") {
stack.push(stack.pop() * stack.pop());
} else if (token === "/") {
const secondOperand = stack.pop();
const firstOperand = stack.pop();
stack.push(Math.trunc(firstOperand / secondOperand));
} else {
stack.push(parseInt(token));
}
}
return stack.pop();
};
class Solution:
def evalRPN(self, tokens: List[str]) -> int:
stack = []
for token in tokens:
if token == "+":
stack.append(stack.pop() + stack.pop())
elif token == "-":
second_operand = stack.pop()
first_operand = stack.pop()
stack.append(first_operand - second_operand)
elif token == "*":
stack.append(stack.pop() * stack.pop())
elif token == "/":
second_operand = stack.pop()
first_operand = stack.pop()
stack.append(int(first_operand / second_operand))
else:
stack.append(int(token))
return stack.pop()
class Solution {
public:
int evalRPN(vector<string>& tokens) {
stack<int> s;
for (const string& token : tokens) {
if (token == "+") {
int second_operand = s.top();
s.pop();
int first_operand = s.top();
s.pop();
s.push(first_operand + second_operand);
} else if (token == "-") {
int second_operand = s.top();
s.pop();
int first_operand = s.top();
s.pop();
s.push(first_operand - second_operand);
} else if (token == "*") {
int second_operand = s.top();
s.pop();
int first_operand = s.top();
s.pop();
s.push(first_operand * second_operand);
} else if (token == "/") {
int second_operand = s.top();
s.pop();
int first_operand = s.top();
s.pop();
s.push(first_operand / second_operand);
} else {
s.push(stoi(token));
}
}
return s.top();
}
};
Time/Space Complexity:
- Time Complexity: O(n)
- Space Complexity: O(n)
Explanation:
Space and time complexity are proportional to the number of tokens, so we get a linear complexity. Generally, stack is the best candidate for a data structure for this problem, since it allows us to simulate the reverse polish notation. If we have a number as a token, we parse it and push
it to the stack, if however, we have an operation we pop
two operands from the top of the stack and do the operations on them, pushing back their result to the stack. Note that addition and multiplication are commutative operations, so the order of operands is not important, while for subtraction and division the order of operands is important. We use two variables secondOperand
and firstOperand
to order the operands correctly. Finally, we pop
the last element on the stack which is also our result after all operations have been executed. Note that we also don't do any validation on the tokens or check if we have valid expression, since by the rules given as part of the problem, we will always have valid expression.