Evaluate Reverse Polish Notation
Compute the value of a postfix expression
DSA, Medium, Stack
Which structure or algorithm, and what does it cost.
A list tokens holds a postfix expression. Each token is a whole number written as a string, or one of the operators +, -, *, /. An operator applies to the two values that came just before it, with the earlier value on the left. Division drops the fractional part, so it rounds toward zero. Return the value of the whole expression as a whole number. The expression is always valid and never divides by zero.
Examples
Constraints
- 1 <= number of tokens <= 100,000.
- Each number is a whole number between -1,000,000 and 1,000,000.
- Every value during the calculation fits in a signed 64-bit integer.
Your answer must contain
- The simple method and why it is too slow; the method; code; time and memory cost; a hand trace of example 1.
Target Aim for O(n) time and O(n) memory.
Hints
Try the problem first. Open one hint at a time.
Hint 1 a nudge
Read the tokens from left to right. When you meet a number, you cannot use it yet. Where could you keep it until an operator needs it?
Hint 2 the approach
An operator always works on the two most recent values that are still unused. Keep the unused values so that the newest one is the first you take back.
Hint 3 the key step
Push each number. An operator takes back the two newest values. Which came first, and why does that matter for minus and divide? Check how -9 / 4 rounds.
Walkthrough
Full walkthrough brute force to best
Brute force
Scan the list for the first operator. Apply it to the two tokens before it, and replace those three tokens with the result. Repeat until one token is left. Each pass scans and shifts the list, so this is O(n^2) time. With 100,000 tokens, where all numbers come before all operators, that is about 2.5 billion steps.
Best method
Keep a stack of values that are waiting for an operator. A number goes on the stack. An operator takes the top two values: the top one is the right side and the one under it is the left side. Apply the operator and push the answer, which can be an input to a later operator. In a valid expression the two values are always there, and one value is left at the end. That value is the answer. Division needs care. Divide the absolute values and give the result the sign of the true quotient, so it rounds toward zero. Floor division would turn -2.25 into -3.
Hand trace
Run on [7, 2, -, 4, *]. Token 7: push. Stack [7]. Token 2: push. Stack [7, 2]. Token -: pop 2 as the right side and 7 as the left side. 7 - 2 is 5, so push 5. Stack [5]. Token 4: push. Stack [5, 4]. Token *: pop 4 as the right side and 5 as the left side. 5 * 4 is 20, so push 20. Stack [20]. The answer is 20.
Code
def eval_rpn(tokens):
stack = []
for token in tokens:
if token not in ("+", "-", "*", "/"):
stack.append(int(token))
continue
right = stack.pop()
left = stack.pop()
if token == "+":
stack.append(left + right)
elif token == "-":
stack.append(left - right)
elif token == "*":
stack.append(left * right)
else:
quotient = abs(left) // abs(right) # round toward zero
stack.append(quotient if (left < 0) == (right < 0) else -quotient)
return stack[0]Time and memory
O(n) time, because each token is handled once and every push or pop is O(1). O(n) memory, because a long run of numbers before the first operator keeps them all on the stack.
Common mistakes
- Swapping the two sides. For minus and divide the order matters: the value that came first is the left side.
- Using floor division. With -9 and 4 it gives -3, but the answer must round toward zero and give -2.
- Deciding what is a number by its first character or by a digits-only test. The token "-9" is a number. Test for the four operator tokens, and treat everything else as a number.