Skip to problem
←

Evaluate Reverse Polish Notation

Medium 0 attempts

You're given an arithmetic expression written in Reverse Polish (postfix) Notation as a list of tokens. Compute its value, where the supported operators are +, -, *, and /, and division between two integers truncates toward zero rather than rounding down.

Each operator applies to the two preceding results: pop the right operand first, then the left. For example, ["3", "7", "-"] means 3 - 7, and ["-7", "3", "/"] evaluates to -2. The expression is valid and never divides by zero.

Function contract

tokens is a valid postfix expression. Each token is an integer string or one of +, -, *, /.

Output: Return the integer value of the expression; division truncates toward zero.

Example 1

Input
tokens = ["2","1","+","3","*"]
Output
9

Explanation: The expression is (2 + 1) × 3 = 9.

Example 2

Input
tokens = ["4","13","5","/","+"]
Output
6
Constraints
  • 1 <= tokens.length <= 10^4
  • tokens[i] is an operator or integer in [-200, 200]
  • The expression is valid and never divides by zero.
  • Every intermediate result and the final answer fit in a signed 32-bit integer.
Topics

Stack

Push numbers. For an operator, pop its right operand and then its left operand, evaluate, and push the result. Math.trunc handles negative division correctly.

javascript
function evalRPN(tokens) {
  const stack = [];
  for (const t of tokens) {
    if ('+-*/'.includes(t)) {
      const b = stack.pop(),
        a = stack.pop();
      if (t === '+') stack.push(a + b);
      else if (t === '-') stack.push(a - b);
      else if (t === '*') stack.push(a * b);
      else stack.push(Math.trunc(a / b));
    } else stack.push(Number(t));
  }
  return stack[0];
}

Time: O(n) | Space: O(n)

Loading discussion…

Saved in this browser only. Private to you.

JavaScript