Problem
Evaluate an arithmetic expression written in reverse Polish notation. The valid operators are +, -, * and /, and division between two integers truncates toward zero.
Examples
Example 1
`tokens = ["2", "1", "+", "3", "*"]``9`((2 + 1) * 3) = 9
Example 2
`tokens = ["4", "13", "5", "/", "+"]``6`(4 + (13 / 5)) = 6, because division truncates toward zero.
Example 3
`tokens = ["10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"]``22`Constraints
1 <= tokens.length <= 10^4tokens[i]is either an operator:"+","-","*", or"/", or an integer in the range[-200, 200].
Hints
Hint 1
The operator comes after its two operands. Tokens are already split, so you do not parse spaces. The expression is valid and there is no division by zero.
Hint 2
Postfix evaluation is the classic stack walk: numbers go on the stack, operators consume the top two values.
Solution
Tried it yourself? The approach, complexity, and code stay hidden until you choose.
Approach
Brute force. Rewriting to an infix tree and evaluating it is more work than a single stack.
Optimal. One pass over the tokens with a stack of longs or ints, popping the right operand first so subtraction and division keep the correct order.
Alternative. A recursive evaluator can consume the token list from the right, which is equivalent and uses the call stack.
Complexity
- Time
- O(n)
O(n) time and O(n) space.
- Space
- O(n)
Code
def eval_rpn(tokens: list[str]) -> int:
stack: list[int] = []
for tok in tokens:
if tok not in {"+", "-", "*", "/"}:
stack.append(int(tok))
continue
b = stack.pop()
a = stack.pop()
if tok == "+":
stack.append(a + b)
elif tok == "-":
stack.append(a - b)
elif tok == "*":
stack.append(a * b)
else:
stack.append(int(a / b)) # truncates toward zero
return stack[-1]
if __name__ == "__main__":
assert eval_rpn(["2", "1", "+", "3", "*"]) == 9
assert eval_rpn(["4", "13", "5", "/", "+"]) == 6
assert eval_rpn(["10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"]) == 22
print("ok")import java.util.ArrayDeque;
import java.util.Set;
public class EvaluateReversePolishNotation {
static int evalRPN(String[] tokens) {
var stack = new ArrayDeque<Integer>();
var ops = Set.of("+", "-", "*", "/");
for (var tok : tokens) {
if (!ops.contains(tok)) {
stack.addLast(Integer.parseInt(tok));
continue;
}
int b = stack.removeLast();
int a = stack.removeLast();
switch (tok) {
case "+" -> stack.addLast(a + b);
case "-" -> stack.addLast(a - b);
case "*" -> stack.addLast(a * b);
case "/" -> stack.addLast(a / b);
default -> throw new IllegalArgumentException(tok);
}
}
return stack.removeLast();
}
public static void main(String[] args) {
if (evalRPN(new String[] {"2", "1", "+", "3", "*"}) != 9) throw new AssertionError();
if (evalRPN(new String[] {"4", "13", "5", "/", "+"}) != 6) throw new AssertionError();
if (evalRPN(new String[] {"10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"}) != 22)
throw new AssertionError();
System.out.println("ok");
}
}Edge cases
- Official samples: ["2","1","+","3",""] equals 9, ["4","13","5","/","+"] equals 6, and ["10","6","9","3","+","-11","","/","*","17","+","5","+"] equals 22.
- Division truncates toward zero, so in Python you must use an integer truncation, not floor division, when a negative operand is present.
- Pop the right operand first.
Follow-ups
- Infix evaluation with operator precedence is Basic Calculator II; adding parentheses is Basic Calculator.
Interview script
"Reverse Polish notation is evaluated with a stack. Numbers are pushed, and an operator pops the right operand, then the left, and pushes the result. I am careful that Java integer division already truncates toward zero, and that a Python solution must not use floor division."
Sources (1)
- LeetCode 150: Evaluate Reverse Polish Notationleetcode.com