MediumStacks QueuesAI interview only
Evaluate Reverse Polish Notation
Asked atamazongooglemicrosoftlinkedinbloombergoracle
01 · Problem
You are given an array of strings tokens that represents an arithmetic expression in Reverse Polish Notation.
Evaluate the expression and return an integer that represents the value of the expression.
Note that:
- The valid operators are
'+','-','*', and'/'. - Each operand may be an integer or another expression.
- The division between two integers always truncates toward zero.
- There will not be any division by zero.
- The input represents a valid arithmetic expression in reverse polish notation.
- The answer and all the intermediate calculations can be represented in a 32-bit integer.
02 · Examples
Example 01
Input
tokens = ["2","1","+","3","*"]
Output
9
((2 + 1) * 3) = 9
Example 02
Input
tokens = ["4","13","5","/","+"]
Output
6
(4 + (13 / 5)) = (4 + 2) = 6. Division truncates toward zero.
Example 03
Input
tokens = ["10","6","9","3","+","-11","*","/","*","17","+","5","+"]
Output
22
((10 * (6 / ((9 + 3) * -11))) + 17 + 5) = ((10 * 0) + 17 + 5) = 22
03 · Constraints
- 011 <= tokens.length <= 104
- 02tokens[i] is either an operator: "+", "-", "*", or "/", or an integer in the range [-200, 200].
- 03The input represents a valid arithmetic expression in reverse polish notation.
- 04The answer and all intermediate calculations can be represented in a 32-bit integer.
04 · Optimal complexity
- Time
- O(n)
- Space
- O(n)
05 · Two ways to work on it
Practice it alone or rehearse it as an interview.
Practice Mode gives you an editor and test runs, nothing else. AI Interview Mode puts a voice interviewer on the other side, adds a clock, and ends with a scored summary of the round.