Evaluate Reverse Polish Notation

Medium

Topics
ArrayStackMath

Evaluate an arithmetic expression in Reverse Polish Notation given as a list of tokens. Valid operators are + - * /; division truncates toward zero.

Example 1

21+3*
operator
In postfix the operator comes after its two operands, so no brackets and no precedence rules are needed. Push each number; on an operator pop two, apply, push the result. The last value left is the answer, 9. Order matters for - and /: the first popped value is the right operand.
Each chip is one token, left to right.
Input:  tokens = ["2","1","+","3","*"]
Output: 9

Example 2

4135/+
operator
Input:  tokens = ["4","13","5","/","+"]
Output: 6

Constraints

  • 1 <= tokens.length <= 10^4
  • Tokens are integers or one of + - * /.
Editorial — intuition, approach, complexity and pitfalls

Intuition

In postfix notation an operator applies to the two most recent results — exactly stack behaviour. Push numbers; on an operator, pop two and push the result.

Approach

  1. Scan tokens with a stack.
  2. On a number, push it.
  3. On an operator, pop the top two (order matters for - and /), compute, and push back.

Dry Run

tokens 4 13 5 / +
  4    push                      stack [4]
  13   push                      stack [4, 13]
  5    push                      stack [4, 13, 5]
  /    pop 5, then pop 13        the SECOND pop is the left operand
       13 / 5 = 2                stack [4, 2]
  +    pop 2, then pop 4
       4 + 2 = 6                 stack [6]
answer 6
Pop order is the thing to get right. The stack hands back the most recent value
first, so the first pop is the RIGHT operand -- which matters not at all for + and
*, and entirely for - and /. Reversing them turns 13 / 5 into 5 / 13.
Division truncates toward zero, which is not what Python's `//` does on negatives.
`int(a / b)` gives -3 for -7 / 2 where `//` gives -4; on this input both happen to
agree at 6, so the bug hides until a negative appears.
No parentheses and no precedence rules exist in RPN -- the order is already
encoded in the token sequence, which is why a single stack and one pass suffice
with no parser.

Complexity

  • Time — O(n): one pass over the tokens.
  • Space — O(n): the operand stack.

Common Pitfalls

  • Division truncates toward zero (use int(a/b) in Python, not floor division for negatives).

Full Solution — all languages

class Solution:
    def evalRPN(self, words):
        stack=[]
        for tok in words:
            if tok in ('+','-','*','/'):
                b=stack.pop(); a=stack.pop()
                if tok=='+': stack.append(a+b)
                elif tok=='-': stack.append(a-b)
                elif tok=='*': stack.append(a*b)
                else: stack.append(int(a/b))
            else: stack.append(int(tok))
        return stack[0]
SensAI
Beta
Tap the mic to stop voice mode