LeetCode #150 Medium

Evaluate Reverse Polish Notation

Evaluate Reverse Polish Notation is LeetCode 150 (Medium). You get an array of string tokens that spells an arithmetic expression in postfix form, where each operator comes after its two operands. Return the value of the expression as an integer.

  • The operators are +, -, * and /. Any other token is an integer, and it may be negative.
  • Division between integers truncates toward zero.
Constraints
  • 1 <= tokens.length <= 10⁴
  • tokens[i] is "+", "-", "*", "/", or an integer in the range [-200, 200]
  • The expression is valid, never divides by zero, and every result fits in a 32-bit int
stackmathstrings
Open on LeetCode ↗
02

Intuition

In postfix form an operator always applies to the two most recent values that are still unused. A stack keeps exactly those values on top, so one pass is enough: push each number, and on an operator pop two values, combine them, and push the result back. The result becomes an ordinary value that a later operator can use.

  • Order: the first value popped is the right operand. 5 3 - means 5 − 3, not 3 − 5.
  • Division: the result drops its fraction, so −7 / 2 is −3, not −4.

A valid expression leaves exactly one value on the stack, and that value is the answer.

How to spot this pattern

Tokens arrive with each operator after its operands, and nothing ever needs brackets or precedence rules. Each operator closes off the two values just before it, which is last-in, first-out: a stack.

03

Approach

Try it first

Before reading on, decide which of the two popped values is the left operand, and what −7 / 2 should return here. Aim for O(n) time.

1

Push every number

Walk the tokens left to right. If a token is not one of the four operator strings, convert it with int and push it. A number cannot be used until an operator arrives, so it waits on the stack.

2

Pop the right operand, then the left

On an operator, pop once into b and once more into a. The value pushed last sits on top, and it is the one written last in the expression, so it is the right-hand side.

3

Combine and push the result back

Compute a + b, a - b, a * b or int(a / b) and push it. Pushing it back lets a later operator use it as one of its own operands, which is how nested expressions like (2 + 1) × 3 are built.

4

Return the last value

After the final token the stack holds one value. Every operator removed two values and added one, and a valid expression has exactly one more number than operators, so one value is left.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def evalRPN(self, tokens: List[str]) -> int:
▶3 ops = {"+", "-", "*", "/"}
▶4 stack = []
▶5 for t in tokens:
▶6 if t not in ops:
▶7 stack.append(int(t))
▶8 continue
▶9 b = stack.pop()
▶10 a = stack.pop()
▶11 if t == "+":
▶12 stack.append(a + b)
▶13 elif t == "-":
▶14 stack.append(a - b)
▶15 elif t == "*":
▶16 stack.append(a * b)
▶17 else:
▶18 stack.append(int(a / b))
▶19 return stack[0]
tokens21+3×stack, top on the rightemptystack is empty → read the tokens left to right
tokens5
stackempty
The stack will hold every value that is waiting for an operator. Nothing is waiting yet.
tokens2now1+3×stack, top on the right2pushed2 is a number → push it
token"2"
stack size1
A number cannot be used until an operator arrives, so it waits on top of the stack.
tokens21now+3×stack, top on the right21pushed1 is a number → push it
token"1"
stack size2
A number cannot be used until an operator arrives, so it waits on top of the stack.
tokens21+now3×stack, top on the right2left1right2popped 2nd+1popped 1st=add → pop 1 (right), then 2 (left)
b1popped first
a2popped second
The top value 1 was written last, so it is the right operand. The value under it, 2, is the left one.
tokens21+now3×stack, top on the right3result2left+1right=3pushed2 + 1 = 3 → push 3
result3
stack size1
2 + 1 = 3. The result goes back on the stack, so a later operator can use it as an operand.
tokens21+3now×stack, top on the right33pushed3 is a number → push it
token"3"
stack size2
A number cannot be used until an operator arrives, so it waits on top of the stack.
tokens21+3×nowstack, top on the right3left3right3popped 2nd×3popped 1st=multiply → pop 3 (right), then 3 (left)
b3popped first
a3popped second
The top value 3 was written last, so it is the right operand. The value under it, 3, is the left one.
tokens21+3×nowstack, top on the right9result3left×3right=9pushed3 × 3 = 9 → push 9
result9
stack size1
3 × 3 = 9. The result goes back on the stack, so a later operator can use it as an operand.
tokens21+3×stack, top on the right9answerno tokens left, one value → answer 9
answer9
Each operator took two values and gave back one, so a valid expression ends with exactly one value. That value is the whole expression.
05

Common pitfalls

Popping the operands in the wrong order

✗ Wrong
a = stack.pop()
b = stack.pop()
✓ Right
b = stack.pop()
a = stack.pop()

+ and * give the same answer either way, so simple tests pass. For ["5", "3", "-"] the swapped version returns 3 − 5 = −2 instead of 2, and ["6", "3", "/"] returns 0 instead of 2.

Using Python's floor division

✗ Wrong
stack.append(a // b)
✓ Right
stack.append(int(a / b))

// rounds toward negative infinity. For ["-7", "2", "/"] it returns −4, but the expected answer is −3. In C++ and Java, / on ints already truncates toward zero.

Spotting numbers by checking for digits

✗ Wrong
if t.isdigit():
✓ Right
if t not in ops:

"-4".isdigit() is false, so ["3", "-4", "-"] sends -4 down the operator branch, which pops from a stack holding only 3 and crashes. Testing against the four operator strings classifies every token correctly.

06

Edge cases

A single number, such as ["18"]

No operator ever runs, so the stack holds 18 and that is returned.

07

Complexity

Time
O(n)
Space
O(n)
Each token is read once and pushed or popped a constant number of times. The stack can hold up to about n / 2 numbers when all the operators come at the end.
08

Evaluate Reverse Polish Notation FAQ

Is int(a / b) safe, given that it divides as floats?

Yes, for this range. With both values inside 32-bit ints, the float quotient is off by far less than the gap to the nearest integer, so dropping the fraction always lands on the right whole number. If you prefer pure integer maths, compute abs(a) // abs(b) and give it a minus sign when exactly one of a and b is negative.

How do I evaluate a normal expression like 3 + 4 * 2 instead?

Ordinary (infix) expressions need precedence and brackets. Either convert to postfix first with the shunting-yard algorithm and then run this stack, or evaluate directly as in Basic Calculator II and Basic Calculator.

What about prefix notation, where the operator comes first?

Read the tokens from right to left with the same stack. Each operator then finds its operands on top, but the first value popped is now the left operand, the reverse of the postfix case.