Evaluate Reverse Polish Notation

Evaluate an arithmetic expression in Reverse Polish Notation.

Pattern

Stack Evaluation

This problem follows the Stack Evaluation pattern, commonly found in the Stack category. Recognizing this pattern is key to solving it efficiently in an interview setting.

Approach

How to Solve It

Push numbers. On operator, pop two operands, compute, push result.

Key Insight

RPN eliminates the need for parentheses and precedence rules — the stack naturally handles evaluation order.

Step-by-step

  1. 1Create an empty stack
  2. 2For each token in the expression:
  3. 3If it's a number, push it onto the stack
  4. 4If it's an operator, pop two operands, apply the operator, push the result
  5. 5The final value on the stack is the answer

Pseudocode

stack = []
for token in tokens:
    if token in {'+', '-', '*', '/'}:
        b, a = stack.pop(), stack.pop()
        if token == '+': stack.push(a + b)
        elif token == '-': stack.push(a - b)
        elif token == '*': stack.push(a * b)
        else: stack.push(int(a / b))  # truncate toward zero
    else:
        stack.push(int(token))
return stack[0]
Complexity Analysis

Time Complexity

O(n)

Space Complexity

O(n)
More Stack Problems

Master this pattern with YeetCode

Practice Evaluate Reverse Polish Notation and similar Stack problems with flashcards. Build pattern recognition through active recall.

Practice this problem