← DSA
MEDIUM

Evaluate Reverse Polish Notation

PracticeNeetCode ↗LeetCode ↗

Evaluate an arithmetic expression given as a list of tokens in Reverse Polish (postfix) notation, where each token is an integer or one of + - * /. Division truncates toward zero.

Example

Input tokens = ["2","1","+","3","*"]
Output 9

Key Pointers

Step-by-Step Analysis

  1. Create an empty stack.
  2. For each token: if it's a number, push it onto the stack.
  3. If it's an operator, pop the top two values (b first, then a), apply the operator as a OP b, and push the result back.
  4. After every token is processed, the one value left on the stack is the answer.

Complexity

Time: O(n) — Space: O(n)

Code

def evalRPN(tokens: list[str]) -> int:
    stack = []

    for token in tokens:
        if token not in {"+", "-", "*", "/"}:
            stack.append(int(token))
            continue

        b = stack.pop()
        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))

    return stack[-1]

Code Explanation

How the solution above works, piece by piece.

  1. In Reverse Polish Notation every operator comes after its two operands, so a stack is all you need: no parentheses or precedence rules.
  2. A number is pushed as an int.
  3. An operator pops b first, then a. Order matters for - and /: the expression is a op b.
  4. int(a / b) truncates toward zero, which the problem requires. Python's // would round -7 // 2 down to −4 instead of −3.
  5. The last value left is the answer. O(n) time, O(n) stack.

Visual Walkthrough

Running it on tokens = ["2", "1", "+", "3", "*"]:

Stack after each token of 2 1 + 3 *22push112push+32 + 1 = 3333push*93 * 3 = 9
Numbers are pushed. An operator pops the top two (the second pop is the left operand), applies itself and pushes the result. The final value on the stack, 9, is the answer: (2 + 1) × 3.
pushed numberresult of an operator

Video Explanation

NeetCode — Evaluate Reverse Polish Notation, LeetCode 150