CodePark/ problems / Evaluate Reverse Polish Notation
START PRACTICINGPRACTICE
Coding problem · Data structures and algorithms › Stacks

Evaluate Reverse Polish Notation

mediumabout 20 minutes in an interview

In reverse Polish notation (RPN), an operator comes after its two operands. For example, 3 4 + means 3 + 4, and 3 4 + 2 * means (3 + 4) * 2. No brackets are needed.

You get the expression as an array of string tokens. Return its value as a number.

  • Tokens are integers, or one of the operators "+", "-", "*", "/". Integers may be negative, like "-4".
  • For a b -, the result is a - b. For a b /, it is a / b. The first operand is the one written first.
  • Dividing keeps only the whole-number part and rounds toward zero: 7 / -2 is -3, not -4.
  • You can trust the input. It is a well-formed expression with at least one token, and no division ever has 0 on the right.
Input: tokens = ["3", "4", "+", "2", "*", "7", "-"] Output: 7(3 + 4) * 2 - 7 = 7
Input: tokens = ["7", "-2", "/"] Output: -3
Input: tokens = ["42"] Output: 42