v9.1.1
Menu

Evaluate Reverse Polish Notation

mediumFREEStacks & QueuesMicrosoft DSA

Evaluate an arithmetic expression in Reverse Polish Notation (postfix). Valid operators: +, -, *, /. Division truncates toward zero.

eval_rpn(tokens) receives tokens as a list of strings; each is an integer (which may be negative, e.g. "-11") or an operator. Return the value of the expression as an integer.

Example

Input
2,1,+,3,*
Output
9
Reasoning
  • The input tokens is a sequence of strings read left to right: 2, 1, +, 3, *. Each string is either an integer (possibly negative) or one of the four operators.
  • In postfix, an operator acts on the two values that come directly before it, where a value is either a number or the result of an earlier operator. Nothing waits on precedence or parentheses.
  • The first operator is +, applied to 22 and 11: 2+1=32 + 1 = 3. That result now stands in for the three tokens 2, 1, +.
  • Next comes 3, then *, which acts on the earlier result 33 and the new 33: 3×3=93 \times 3 = 9. All tokens are used and exactly one value remains, so the output is the integer 9. In infix this is (2+1)×3(2 + 1) \times 3.
  • Notice that order matters for −- and ÷\div: the value that appeared earlier is the left operand. Division truncates toward zero, so 13÷5=2.613 \div 5 = 2.6 becomes 22, and 7÷(−2)=−3.57 \div (-2) = -3.5 becomes −3-3, not −4-4.

Constraints

  • 1 <= len(tokens) <= 10^4
  • Tokens are integers or operators

Learn this in

More from Microsoft DSA

solution.py

Test results

Sign in to run your code against the test cases.