We are given a mathematical expression, but not in the usual infix notation like (2 + 1) * 3. Instead, it is written in Reverse Polish Notation (RPN), also called postfix notation. In RPN, the operator comes after its two operands. So 2 + 1 becomes 2 1 +, and (2 + 1) * 3 becomes 2 1 + 3 *.
RPN needs no parentheses. The order of operations is determined entirely by the position of operators relative to operands. Each operator applies to the two most recent operands, and that "last in, first out" access pattern maps directly to a stack.
[-200, 200] and the problem's guarantee that every intermediate result fits in a 32-bit integer mean a plain int works in every language. No overflow handling needed.// floors toward negative infinity, so int(a / b) is required. In JavaScript and TypeScript, / produces a float, so Math.trunc is required.Consider the expression ["2","1","+","3","*"], which represents (2 + 1) * 3. As we scan from left to right:
2, then 1. These are numbers, so we hold on to them.+. This adds the last two numbers, giving 2 + 1 = 3. We replace 2 and 1 with that single result, 3.3, another number, which we hold alongside the running result 3.*. We multiply the last two numbers, 3 * 3 = 9, which is the answer.Numbers accumulate, and each operator consumes the top two. A stack matches this directly: numbers get pushed, operators pop two values, compute a result, and push it back. After processing every token, the stack holds exactly one element, the final answer.
The one detail to get right is operand order. When we pop two values for subtraction or division, the first popped value is the right operand and the second popped value is the left operand. For 5 3 -, we want 5 - 3 = 2, not 3 - 5 = -2. Since 3 was pushed last, it pops first, so the computation is secondPopped - firstPopped.
Each operator consumes two operands and produces one result, so the stack grows by one for every number and shrinks by one for every operator. A valid RPN expression with k numbers has exactly k-1 operators, so the stack ends with one element. Every operator also finds at least two values waiting, because validity guarantees each operand was produced before the operator that uses it.
Operand order matters because subtraction and division are not commutative. In ["5","3","-"], we push 5 then 3, so 3 pops first as b and 5 pops second as a. The computation a - b = 5 - 3 = 2 is correct, while b - a = 3 - 5 = -2 is not.
+, -, *, /), pop the top two elements from the stack. Call them b (first pop, right operand) and a (second pop, left operand).a op b.