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.
- 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
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.
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.
Approach
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.
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.
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.
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.
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.
Code in Python, C++ and Java
// does, would give −4.Common pitfalls
Popping the operands in the wrong order
a = stack.pop() b = stack.pop()
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
stack.append(a // b)
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
if t.isdigit():
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.
Edge cases
No operator ever runs, so the stack holds 18 and that is returned.
Complexity
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.