Expression / Call Stack

Evaluate Reverse Polish Notation

Medium
Solve it on LeetCode ↗

The problem

Evaluate a postfix expression given as tokens (e.g. ["2","1","+","3","*"] = 9). Division truncates toward zero.

Stuck? Reveal hints one at a time

How to approach it

  1. 1Scan tokens. Numbers → push.
  2. 2Operator → pop b then a, compute a op b, push the result.
  3. 3One value remains at the end — the answer.

Key insight

RPN is what compilers reduce infix to precisely because a single stack evaluates it in one pass with zero grammar.

The solution

Watch out for

  • Python’s // floors toward −∞; the problem wants truncation toward zero — use int(a/b).
  • Negative numbers arrive as tokens like "-3": test for operators, not for "starts with -".