AceYourInterviews
Checking sign-in…

43. Evaluate Reverse Polish Notation

IntermediateCompleted-subexpression value stack with checked long arithmetic

Evaluate an expression written in reverse Polish notation: an operator comes after its two operands. Every operator combines the two most recent completed values in the appropriate left-to-right operand order.

Subtraction and division depend on operand order. Reject malformed expressions and preserve the contract's overflow and division-error behavior rather than silently wrapping values.

Example 1

Input

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

Output

9

Explanation: First complete 2+1, then multiply that value by three.

Example 2

Input

["7","-3","/"]

Output

-2

Explanation: Java signed integer division truncates toward zero, not toward negative infinity.

Constraints

  • 0 <= tokens.length <= 105
  • sum(tokens[i].length) <= 106
  • -263 <= integer token <= 263 - 1
  • Allowed operators are +, -, * and /. Division truncates toward zero; invalid expressions and arithmetic overflow raise errors.
Hints
Hint 1

Which completed subexpression is at the top when an operator arrives?

Hint 2

Name the first popped value right and the next left.

Hint 3

Reduce with checked arithmetic and require one final value.

Practice on LeetCode ↗
Code
Saved on this deviceLn 1, Col 1

Reduce completed child expressions

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