Skip to content

Evaluate Reverse Polish Notation

Evaluate a postfix expression by pushing numbers and applying each operator to the top two values.

MediumStacks
Solve on LeetCode

The problem

You get an arithmetic expression in Reverse Polish Notation as an array of string tokens, where every operator comes after its two operands. The tokens are integers and the operators +, -, * and /, and division between two integers truncates toward zero. Return the value of the expression; you can assume it is valid, never divides by zero, and every intermediate result fits in a 32-bit integer.

Input tokens = ["7", "2", "3", "*", "-"]

Output 1

The `*` uses the two values just before it, 2 * 3 = 6, and then `-` gives 7 - 6 = 1.

Input tokens = ["-9", "2", "/", "6", "+"]

Output 2

-9 / 2 truncates toward zero to -4 (not -5), and -4 + 6 = 2.

Key constraint: Numbers can be negative and division truncates toward zero, so -9 / 2 must give -4.

How to spot the pattern

  • Each operator applies to the two most recent values that haven't been used yet.
  • Results feed into later operations, so partial values are needed again in last-in, first-out order.

The idea

In postfix order, an operator always works on the two values produced just before it. So read the tokens from left to right and push every number onto a stack. When an operator appears, pop the top two values, apply the operator and push the result back, because it becomes an operand for a later operator. After the last token, the one value left on the stack is the answer.

Brute force: Repeatedly find the first operator, replace it and its two operands with the result and rebuild the list, which costs O(n^2) time.

Step by step

  1. 1Create an empty stack of integers.
  2. 2If the token is a number, push its integer value.
  3. 3If the token is an operator, pop b (the right operand) first, then a, and push the result of a op b.
  4. 4For /, divide and truncate the result toward zero.
  5. 5After the last token, return the only value on the stack.

See the pattern move

The stacks pattern on a small example. Step through it, or press play.

Code

class Solution:
    def evalRPN(self, tokens: List[str]) -> int:
        stack = []
        for token in tokens:
            if token in ("+", "-", "*", "/"):
                b = stack.pop()  # right operand comes off first
                a = stack.pop()
                if token == "+":
                    stack.append(a + b)
                elif token == "-":
                    stack.append(a - b)
                elif token == "*":
                    stack.append(a * b)
                else:
                    stack.append(int(a / b))  # truncate toward zero, unlike //
            else:
                stack.append(int(token))
        return stack[-1]

Complexity

Time

O(n)

Space

O(n)

Each token is pushed or popped a constant number of times; the stack holds at most about half of the tokens, the numbers.

Watch out for

  • Popping the operands in the wrong order: the first pop is the right operand, so a - b and a / b come out reversed otherwise.
  • Using Python's //, which rounds down: -9 // 2 is -5, but the answer needs -4, so use int(a / b).
  • Spotting operators by checking whether the token starts with -, which also matches negative numbers like -9.

Follow-up questions

How would you turn a normal expression like 3 + 4 * 2 into postfix?

Use the shunting-yard idea: write numbers to the output right away, keep operators on a stack, and before pushing an operator, pop every operator on the stack with higher or equal precedence to the output. Parentheses work as markers on the same stack.

What if the expression could be invalid?

Check that the stack holds at least two values before every operator and exactly one value at the end, and report an error otherwise; also reject a division by zero.

In Hinglish

Number aaye toh stack mein daalo. Operator aaye toh upar ke do number nikalo, pehle nikla wala right side ka hai, aur result wapas stack mein daal do.

Related problems