Skip to content

Evaluate Reverse Polish Notation

MediumStack
Decode it first. Clues, constraints, pattern and plan before any code.

In Reverse Polish Notation (RPN), an operator comes after its two operands: 3 4 + means 3 + 4, and 2 1 + 3 * means (2 + 1) * 3. Given a list of string tokens in RPN, return the value of the expression as an integer.

The operators are +, -, * and /. Division between two integers truncates toward zero (so 7 / -3 is -2, not -3).

["2", "1", "+", "3", "*"]      →  9    ((2 + 1) * 3)
["4", "13", "5", "/", "+"]     →  6    (4 + 13 / 5)
["7", "-3", "/"]              →  -2

Constraints

  • 1 <= tokens.length <= 10^4
  • Each token is an operator or an integer in the range [-200, 200].
  • The expression is always valid and never divides by zero.
  • Every intermediate value fits in a 32-bit integer.