43. Evaluate Reverse Polish Notation
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 <= 105sum(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.
Submissions
Your recent submissions for this problem.
Checking sign-in…
Discussion
Ask a question or share an approach. Posts are public; avoid personal information and mark solution spoilers clearly.
No discussion yet. Start the conversation with a question about this problem.
Checking sign-in…
Run your code to check the sample cases, or submit it to check the full validation suite.
Reduce completed child expressions
["2","1","+","3","*"]
9