In Reverse Polish Notation an operator comes after the two values it works on. So 3 4 + means 3 + 4, and 3 4 + 2 * means (3 + 4) × 2. No brackets are ever needed, because the order of the tokens already says what to do first.
You get such an expression as a list of string tokens, tokens. Each token is a whole number or one of +, -, * and /. Work out the value of the expression and return it as an integer. Division drops any fraction, rounding toward zero, so 7 / -3 is -2.
Example 1
Input: tokens = ["3", "4", "+", "2", "*"] Output: 14 Why: (3 + 4) * 2 = 14
2 more examples and the constraints
Example 2
Input: tokens = ["15", "7", "2", "-", "/"] Output: 3 Why: 15 / (7 - 2) = 15 / 5 = 3
Example 3
Input: tokens = ["7", "-3", "/", "4", "+"] Output: 2 Why: 7 / -3 is -2 after dropping the fraction; -2 + 4 = 2
Constraints
- 1 ≤ length of tokens ≤ 10,000
- Each token is
+,-,*,/or a whole number from −200 to 200 - The expression is always well formed and never divides by zero
- Every value along the way fits in a 32-bit signed integer
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Fold the first operator, repeatO(n²)
- One stack, one passO(n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 10,000 tokens | Verdict |
|---|---|---|---|
| Fold the first operator, repeat | O(n²) | Correct, but rescans the list | |
| One stack, one pass | O(n) | Best; the standard answer |
n = number of tokens.
Edge cases to test
- A single number. ["42"] has no operator; the answer is 42.
- Negative numbers. "-3" is a number, not the minus operator. Check the whole token, not its first character.
- Operand order. ["5", "8", "-"] is 5 − 8 = -3, not 3. The value popped first is the right-hand one.
- Division with a negative result. ["-7", "2", "/"] is -3, not -4: round toward zero.
Common mistakes
- Popping in the wrong order, so
a - banda / bcome out asb - aandb / a. - Treating any token that starts with
-as an operator, which breaks on "-3". - Using floor division (
//in Python), which rounds negative results the wrong way.
How to talk through it
- 1Clarify. Is the expression always valid? How should division round? Can a number be negative?
- 2Give the slow idea. Fold the first operator with the two numbers before it and repeat; say it is O(n²).
- 3Spot the stack. An operator uses the two newest unused values, which is last in, first out.
- 4Code the pass. Push numbers; on an operator pop
b, thena, pusha op b. Point out the pop order. - 5Test out loud. Run a single number, a subtraction, and a negative division before you finish.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?