CodingNodes / Stack / Evaluate Reverse Polish Notation System design Space play · ←→ step · R restart

Problem

An arithmetic expression is written in postfix form: each operator comes right after its two operands, so no parentheses are needed. 3 4 + means 3 + 4, and 5 1 2 + * means 5 × (1 + 2).

You get the expression as an array of strings tokens. Each token is an integer or one of + - * /. Return the value of the whole expression.

Division between integers drops the fractional part, rounding toward zero (so 7 / -2 is -3). The input is always a valid expression, never divides by zero, and every intermediate value fits in a 32-bit integer.

Constraints

  • 1 ≤ tokens.length ≤ 10⁴
  • each token is + - * / or an integer in [-200, 200]
  • the expression is valid and never divides by zero

Examples: pick one to animate

Solutions

TimeO(n) SpaceO(n)

Time: Each token is read once. A number costs one push; an operator costs two pops, one arithmetic step and one push, all O(1).

Space: The stack holds numbers that are still waiting for an operator. With many numbers before the operators that is up to about n/2 entries, which is O(n).

Scan left to right. Push every number. When an operator appears, its operands are the two most recent unused values: pop b (right side) first, then a (left side), compute a op b and push the result. The last value left on the stack is the answer.