SDE & MLE Prep

150. Evaluate Reverse Polish Notation

Problem

Evaluate an arithmetic expression given in Reverse Polish (postfix) notation as a list of tokens: integers and the operators + - * /. Division truncates toward zero. The expression is always valid.

Example: ["2","1","+","3","*"] → 9 (= (2 + 1) × 3)

Push numbers; an operator pops b then a and pushes a op b. Division truncates toward zero.

Complexity: O(n).

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))  # truncate toward 0
            else:
                st.append(int(t))
        return st[0]