Evaluate an arithmetic expression in Reverse Polish Notation.
This problem follows the Stack Evaluation pattern, commonly found in the Stack category. Recognizing this pattern is key to solving it efficiently in an interview setting.
Push numbers. On operator, pop two operands, compute, push result.
RPN eliminates the need for parentheses and precedence rules — the stack naturally handles evaluation order.
stack = []
for token in tokens:
if token in {'+', '-', '*', '/'}:
b, a = stack.pop(), stack.pop()
if token == '+': stack.push(a + b)
elif token == '-': stack.push(a - b)
elif token == '*': stack.push(a * b)
else: stack.push(int(a / b)) # truncate toward zero
else:
stack.push(int(token))
return stack[0]Practice Evaluate Reverse Polish Notation and similar Stack problems with flashcards. Build pattern recognition through active recall.
Practice this problem