SprintCode.pro

Подготовка к алгоритмическим задачам

Super

Evaluate Reverse Polish Notation

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

Example 1:

Input: tokens = ["2","1","+","3","*"]
Output: 9

Example 2:

Input: tokens = ["4","13","5","/","+"]
Output: 6

Constraints:

1 <= tokens.length <= 10⁴

Деление на ноль не встречается

Recommended time and space complexity

O(n) time and O(n) space.


Hint 1

In postfix notation operands come before the operator. Which structure gives you the last two values?


Hint 2

Stack: push numbers, on an operator pop two and push the result.


Hint 3

Order matters: the first popped value is the right operand.

A stack problem. Teaches using a stack machine to evaluate expressions and why postfix notation needs no brackets or precedence.

Expected Input :

["2","1","+","3","*"]

Expected Output

9