Evaluate Reverse Polish Notation
Evaluate Reverse Polish Notation is a medium stack problem solved with the stack basics pattern.
The best approach, optimal (stack), runs in O(n) time and O(n) space.
Problem
Evaluate an arithmetic expression written in Reverse Polish Notation (operators come after their operands). Tokens are integers or one of + - * /. Division truncates toward zero.
Examples
Example 1
- Input
tokens = ["3", "4", "+", "2", "*"]- Output
14- Why
- (3 + 4) * 2.
Example 2
- Input
tokens = ["7", "-2", "/"]- Output
-3- Why
- Division truncates toward zero.
Constraints
1 <= tokens.length <= 10^4- Operators are + - * /; the expression is always valid.
Solve it here
Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.
Your own testcases: Run checks these, and the expected output comes from our reference solution.
My submissions
Nothing yet. Every Run and Submit you make while signed in shows up here.
| When | Result | Tests | Runtime | Your time | Type |
|---|
Run checks the testcases above (2 examples, or your own). Submit also runs 11 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.
Animated walkthrough
A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
Solutions
Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.
| Approach | Time | Space |
|---|---|---|
| Optimal (stack) | O(n) | O(n) |
1Optimal (stack)
O(n)O(n)Push numbers. On an operator, pop b then a (b was pushed last) and push a op b. The single value left is the answer. This is the standard, and only sensible, approach.
- For each token: if it is an operator, pop b, pop a, push a op b.
- Otherwise push Integer.parseInt(token).
- Return the top.
class Solution {
public int evalRPN(String[] tokens) {
Deque<Integer> st = new ArrayDeque<>();
for (String t : tokens) {
switch (t) {
case "+" -> st.push(st.pop() + st.pop());
case "*" -> st.push(st.pop() * st.pop());
case "-" -> { int b = st.pop(), a = st.pop(); st.push(a - b); }
case "/" -> { int b = st.pop(), a = st.pop(); st.push(a / b); }
default -> st.push(Integer.parseInt(t));
}
}
return st.pop();
}
}class Solution:
def evalRPN(self, tokens: List[str]) -> int:
st = []
for t in tokens:
if t == "+":
st.append(st.pop() + st.pop())
elif t == "*":
st.append(st.pop() * st.pop())
elif t == "-":
b, a = st.pop(), st.pop()
st.append(a - b)
elif t == "/":
b, a = st.pop(), st.pop()
st.append(int(a / b)) # truncate toward zero like Java
else:
st.append(int(t))
return st.pop()class Solution {
public:
int evalRPN(vector<string>& tokens) {
vector<int> st;
for (const string& t : tokens) {
if (t == "+" || t == "-" || t == "*" || t == "/") {
int b = st.back(); st.pop_back();
int a = st.back(); st.pop_back();
if (t == "+") st.push_back(a + b);
else if (t == "-") st.push_back(a - b);
else if (t == "*") st.push_back(a * b);
else st.push_back(a / b);
} else {
st.push_back(stoi(t));
}
}
return st.back();
}
};function evalRPN(tokens) {
const st = [];
for (const t of tokens) {
switch (t) {
case "+": st.push(st.pop() + st.pop()); break;
case "*": st.push(st.pop() * st.pop()); break;
case "-": { const b = st.pop(), a = st.pop(); st.push(a - b); break; }
case "/": { const b = st.pop(), a = st.pop(); st.push(Math.trunc(a / b)); break; }
default: st.push(parseInt(t, 10));
}
}
return st.pop();
}Edge cases to test
- Negative number tokens like -2 (not the minus operator)
- Operand order for - and /
Hints
Hint 1
When you see an operator, its two operands are the two most recent values.
FAQ
What is the best time complexity for Evaluate Reverse Polish Notation?
Optimal (stack) runs in O(n) time and O(n) extra space.
Which pattern does Evaluate Reverse Polish Notation use?
It is a stack problem that uses the stack basics pattern. Other problems with the same pattern: Valid Parentheses, Baseball Game, Asteroid Collision.
Which edge cases should I test for Evaluate Reverse Polish Notation?
Negative number tokens like -2 (not the minus operator); Operand order for - and /.