33. Evaluate Reverse Polish Notation
Evaluate an arithmetic expression written in Reverse Polish Notation (operators come after their operands). Operators are + - * /; division truncates toward zero. The expression is always valid.
Example 1
Input:
tokens = ["3","4","+","2","*"]Output:
14Explanation: (3 + 4) × 2 = 14
Example 2
Input:
tokens = ["7","-2","/"]Output:
-3Explanation: 7 / −2 = −3.5, truncated to −3
Hint 1
Numbers go on a stack; an operator pops the top two numbers.
Hint 2
Pop order matters for − and /: the first pop is the right operand.
Approach 1: Stack ✅
Push numbers, apply operators to the top two.
⏱ Time O(n)💾 Space O(n)
Reference solution for Stack (time O(n), space O(n)). Each solution passes every test in all four languages.
class Solution:
def evalRPN(self, tokens: List[str]) -> int:
stack = []
for tok in tokens:
if tok in '+-*/' and len(tok) == 1:
b, a = stack.pop(), stack.pop() # note the order: a op b
if tok == '+': stack.append(a + b)
elif tok == '-': stack.append(a - b)
elif tok == '*': stack.append(a * b)
else: stack.append(int(a / b)) # truncate toward zero
else:
stack.append(int(tok))
return stack[-1]class Solution {
public int evalRPN(String[] tokens) {
Deque<Integer> stack = new ArrayDeque<>();
for (String tok : tokens) {
switch (tok) {
case "+" -> stack.push(stack.pop() + stack.pop());
case "*" -> stack.push(stack.pop() * stack.pop());
case "-" -> { int b = stack.pop(), a = stack.pop(); stack.push(a - b); }
case "/" -> { int b = stack.pop(), a = stack.pop(); stack.push(a / b); }
default -> stack.push(Integer.parseInt(tok));
}
}
return stack.pop();
}
}class Solution {
public:
int evalRPN(vector<string>& tokens) {
vector<long long> st;
for (const string& tok : tokens) {
if (tok.size() == 1 && string("+-*/").find(tok[0]) != string::npos) {
long long b = st.back(); st.pop_back();
long long a = st.back(); st.pop_back();
if (tok == "+") st.push_back(a + b);
else if (tok == "-") st.push_back(a - b);
else if (tok == "*") st.push_back(a * b);
else st.push_back(a / b); // C++ division truncates toward zero
} else st.push_back(stoll(tok));
}
return (int)st.back();
}
};function evalRPN(tokens) {
const stack = [];
for (const tok of tokens) {
if (['+', '-', '*', '/'].includes(tok)) {
const b = stack.pop(), a = stack.pop();
stack.push(tok === '+' ? a + b : tok === '-' ? a - b : tok === '*' ? a * b : Math.trunc(a / b));
} else stack.push(Number(tok));
}
return stack.pop();
}Try solving it yourself first. Interviewers care more about how you explain the approach than about the finished code.
This problem is explained in the lesson Stacks, Queues & Monotonic Stacks.
Run your code to see results here.