sagelearnai

Evaluate Reverse Polish Notation

Difficulty: Medium · Pattern: Stack & Monotonic Stack · LeetCode #150

Evaluate an arithmetic expression written in postfix (Reverse Polish) notation, given as a list of tokens. Operators are + − * /; operands are integers. Division truncates toward zero. The expression is always valid.

Examples

text
["3", "4", "+", "2", "*"]           →  14     ((3 + 4) * 2)
["5", "1", "2", "+", "4", "*", "+", "3", "-"]  →  14   (5 + (1+2)*4 − 3)
["7", "-3", "/"]                    →  −2     (truncate toward zero)

Hints

  1. In postfix, an operator applies to the two most recent values.
  2. Pop the right operand first, then the left one. Order matters for − and /.
  3. Python's // floors (−7 // 3 = −3); you need truncation instead.

Approach

Scan tokens. Push numbers onto a stack. For an operator, pop b (right operand) then a (left operand), compute a op b, and push the result. The final stack holds the answer. Use int(a / b) in Python (or Math.trunc in JS) for truncation toward zero.

Complexity

Time: O(n). Space: O(n).

Python solution
def evalRPN(tokens):
    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 zero
        else:
            st.append(int(t))
    return st[0]
JavaScript solution
function evalRPN(tokens) {
  const st = [];
  for (const t of tokens) {
    if ('+-*/'.includes(t) && t.length === 1) {
      const b = st.pop(), a = st.pop();
      st.push(t === '+' ? a + b : t === '-' ? a - b : t === '*' ? a * b : Math.trunc(a / b));
    } else st.push(Number(t));
  }
  return st[0];
}