Evaluate Reverse Polish Notation (LeetCode 150): Solution and Explanation
You are given an arithmetic expression in postfix form, where each operator comes after its two operands, as a list of tokens. Compute the integer result, where division truncates toward zero.
Watch it run step by step
Try your own input and write the code →Intuition
In ordinary infix notation, like 4 + 13 / 5, you need precedence rules and parentheses to know what to compute first. Postfix notation removes all of that. An operator always applies to the two most recent values that have not been consumed yet, so the expression can be evaluated left to right with no lookahead.
That rule, the two most recent unused values, is exactly what a stack provides. When you see a number, push it. When you see an operator, pop the top two values, apply the operator, and push the result back, because that result is now the most recent unused value. When the tokens run out, the single value left on the stack is the answer.
There is one detail that trips people up: operand order. The top of the stack is the right operand and the value under it is the left operand. For addition and multiplication that does not matter, but for subtraction and division it does. The reference code pops a first and b second, then computes b - a and b / a.
The other detail is division. The problem wants truncation toward zero, like C or Java integer division. Python's // rounds toward negative infinity, so -7 // 2 gives -4 instead of -3. The reference code uses int(b / a), which does true division and then truncates toward zero. In Java and C++, plain integer division already truncates toward zero, so b / a works as written there. It also helps to know what a valid input guarantees. Every operator will find at least two values on the stack, no division by zero occurs, and when the tokens run out exactly one value remains. That means the code needs no defensive checks, and the final answer is simply the only element left on the stack.
Approach: Operand stack
- Create an empty
stack. - For each token
t, if it is+or*, pop two values, combine them, and push the result. Order does not matter for these. - If it is
-, popathenband pushb - a, sinceawas the right operand. - If it is
/, popathenband pushint(b / a)to truncate toward zero. - Otherwise the token is a number, so push
int(t). - After all tokens are processed, return
stack[0].
Step-by-step example
tokens = ["4","13","5","/","+"]
- Push 4, then 13, then 5. The stack is [4, 13, 5].
- Token
/: popa= 5 andb= 13.int(13 / 5)is 2, so push 2. The stack is [4, 2]. - Token
+: pop 2 and 4 and push 6. The stack is [6]. - No tokens remain, so the function returns 6, which matches 4 + (13 / 5) with truncation.
Code: Python, Java, C++
1class Solution:
2 def evalRPN(self, tokens: List[str]) -> int:
3 stack = []
4 for t in tokens:
5 if t == "+":
6 stack.append(stack.pop() + stack.pop())
7 elif t == "-":
8 a, b = stack.pop(), stack.pop()
9 stack.append(b - a)
10 elif t == "*":
11 stack.append(stack.pop() * stack.pop())
12 elif t == "/":
13 a, b = stack.pop(), stack.pop()
14 stack.append(int(b / a))
15 else:
16 stack.append(int(t))
17 return stack[0]1class Solution {
2 public int evalRPN(String[] tokens) {
3 Stack<Integer> stack = new Stack<>();
4 for (String t : tokens) {
5 if (t.equals("+")) {
6 stack.push(stack.pop() + stack.pop());
7 } else if (t.equals("-")) {
8 int a = stack.pop(), b = stack.pop();
9 stack.push(b - a);
10 } else if (t.equals("*")) {
11 stack.push(stack.pop() * stack.pop());
12 } else if (t.equals("/")) {
13 int a = stack.pop(), b = stack.pop();
14 stack.push(b / a);
15 } else {
16 stack.push(Integer.parseInt(t));
17 }
18 }
19 return stack.pop();
20 }
21}1class Solution {
2public:
3 int evalRPN(vector<string>& tokens) {
4 stack<int> stack;
5 for (const string& t : tokens) {
6 if (t == "+" || t == "-" || t == "*" || t == "/") {
7 int a = stack.top(); stack.pop();
8 int b = stack.top(); stack.pop();
9 if (t == "+") stack.push(b + a);
10 else if (t == "-") stack.push(b - a);
11 else if (t == "*") stack.push(b * a);
12 else stack.push(b / a);
13 } else {
14 stack.push(stoi(t));
15 }
16 }
17 return stack.top();
18 }
19};Time and space complexity
O(n)
Each token is processed once, and each push, pop and arithmetic operation is constant time.
O(n)
In the worst case, such as many numbers followed by many operators, about half the tokens sit on the stack at once.
Other approaches
Recursive evaluation from the end (time O(n), space O(n))
Read tokens from the right. An operator's right operand is the subexpression evaluated next, then its left operand. It mirrors the expression tree directly but is less intuitive and uses recursion depth proportional to the expression's nesting.
In-place array as stack (time O(n), space O(1))
Reuse the token array itself, keeping a write index as the top of the stack and overwriting consumed slots with results. It avoids allocating a separate stack, which can matter in a low-memory setting.
Common mistakes
- Swapping operands for subtraction or division. The first value popped is the right operand, so
13 5 -is 13 - 5, not 5 - 13. - Using Python's
//for division, which floors negative results.-7 // 2is -4, but truncation toward zero gives -3. - Checking whether a token is a digit with
t.isdigit(), which fails for negative numbers like -11 and treats them as operators. - Returning the top of the stack without considering that a single-number input is a valid expression whose answer is that number.
Frequently asked questions
Why is a stack used to evaluate Reverse Polish Notation?
Each operator applies to the two most recent values that have not yet been used. A stack gives you exactly those two values on top, and pushing the result keeps the invariant for the next operator.
How do you handle division that truncates toward zero in Python?
Use int(b / a) instead of b // a. Floor division rounds toward negative infinity, which gives the wrong answer when exactly one operand is negative.
What is the time complexity?
It is O(n) time and O(n) space, where n is the number of tokens. Every token causes a constant number of stack operations.
Do I need to worry about operator precedence?
No. Postfix notation encodes the evaluation order in the position of the operators, so there are no precedence rules or parentheses to handle.