Start learning free

LESSON 458 OF 667 · STACK

Evaluate Reverse Polish Notation

Practice O(n)

You get a vector of strings tokens. It holds a math expression in reverse Polish notation (postfix). Return the value of the expression.

In this notation, each operator comes after its two values. 5 + 2 is written 5 2 +. (5 - 1) * 2 is written 5 1 - 2 *. No parentheses are needed.

  • A token is a whole number, like "31" or "-4". Or it is an operator: "+", "-", "*" or "/".
  • An operator uses the two values just before it, in order. 9 4 - means 9 - 4, which is 5.
  • Division rounds toward zero. So 9 / 4 is 2, and -9 / 4 is -2.

 

Example 1:

Input: tokens = ["6", "2", "-", "5", "*"]
Output: 20
Explanation: (6 - 2) * 5 = 20

Example 2:

Input: tokens = ["4", "3", "8", "*", "+", "-5", "2", "/", "-"]
Output: 30
Explanation:
3 8 *   gives 24.
4 24 +  gives 28.
-5 2 /  gives -2 (-2.5 rounded toward zero).
28 -2 - gives 30.

Example 3:

Input: tokens = ["-12"]
Output: -12
Explanation: A single number is already the value.

 

Constraints:

  • tokens has 1 to 100,000 tokens.
  • Every number fits in a 32-bit signed integer, from -231 to 231 - 1.
  • So does every result along the way.
  • The expression is always complete and correct.
  • It never divides by zero.

Note:

Your algorithm should run in O(n) time and use O(n) extra space, where n is the number of tokens.

STEP 1 OF 11
    Ctrl + Enter to check