Back to Problem
Official 901 views

Editorial: Evaluate Reverse Polish Notation

by admin ·

9

1 Intuition

Operands wait on a stack until their operator arrives.

2 Approach

Push numbers; on an operator, pop two values (right operand first), apply it and push the result. Watch out: Python's // floors, so use int(a / b) to truncate.

3 Complexity Analysis

Time O(n), Space O(n).

4 Solution Code

class Solution:
    def evalRPN(self, tokens: list[str]) -> int:
        st = []
        for t in tokens:
            if t in ('+', '-', '*', '/'):
                b, a = st.pop(), st.pop()
                if t == '+': st.append(a + b)
                elif t == '-': st.append(a - b)
                elif t == '*': st.append(a * b)
                else: st.append(int(a / b))
            else:
                st.append(int(t))
        return st[0]

5 Code Walkthrough

The reference solution below implements the approach step by step.