PracticeNeetCode ↗LeetCode ↗
Evaluate an arithmetic expression given as a list of tokens in Reverse Polish (postfix) notation, where each token is an integer or one of + - * /. Division truncates toward zero.
-, /): the second value popped is the left operand, the first value popped is the right operand.b first, then a), apply the operator as a OP b, and push the result back.Time: O(n) — Space: O(n)
def evalRPN(tokens: list[str]) -> int:
stack = []
for token in tokens:
if token not in {"+", "-", "*", "/"}:
stack.append(int(token))
continue
b = stack.pop()
a = stack.pop()
if token == "+":
stack.append(a + b)
elif token == "-":
stack.append(a - b)
elif token == "*":
stack.append(a * b)
else:
stack.append(int(a / b))
return stack[-1]How the solution above works, piece by piece.
int.b first, then a. Order matters for - and /: the expression is a op b.int(a / b) truncates toward zero, which the problem requires. Python's // would round -7 // 2 down to −4 instead of −3.Running it on tokens = ["2", "1", "+", "3", "*"]: