Evaluate Reverse Polish Notation

Difficulty: Medium

You're given an arithmetic expression in postfix notation (also called Reverse Polish Notation), as a list of tokens. Each operator comes right after the two numbers it applies to, so 3 4 + means "3 plus 4". No parentheses are ever needed.

Evaluate the expression and return its value. The operators are +, -, *, and /. Division truncates toward zero (13 / 5 is 2, not 2.6 or 3).

Examples

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

Reading left to right: 2 and 1 combine with + to make 3, then that 3 and the next 3 combine with * to make 9 — this is the postfix form of (2 + 1) * 3.

Input: tokens = ["4", "13", "5", "/", "+"]
Output: 6

13 / 5 truncates to 2, then 4 + 2 = 6.

Input: tokens = ["10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"]
Output: 22

Constraints

  • 1 <= tokens.length <= 10^4

  • Each token is either an operator (+, -, *, /) or an integer.

  • Division always truncates toward zero, and the input never divides by zero.

Approach

Postfix notation can be evaluated in one left-to-right pass with a stack. You never need to think about operator precedence or parentheses.

Walk through the tokens:

  • Number: push it.
  • Operator: pop two numbers. The first one popped is the right-hand operand, the second is the left-hand operand. Apply the operator and push the result.

At the end, exactly one number is left on the stack: the answer.

Solutions

Brute Force — Repeatedly Collapse the First Operator Found

Work on a copy of the tokens. Find the first operator, apply it to the two numbers before it, and splice the result back in. Repeat until one token remains.

function evalRPN(tokens) {
  const ops = new Set(["+", "-", "*", "/"]);
  const arr = [...tokens];

  while (arr.length > 1) {
    const opIndex = arr.findIndex((t) => ops.has(t));
    const b = Number(arr[opIndex - 1]);
    const a = Number(arr[opIndex - 2]);
    let result;
    switch (arr[opIndex]) {
      case "+": result = a + b; break;
      case "-": result = a - b; break;
      case "*": result = a * b; break;
      case "/": result = Math.trunc(a / b); break;
    }
    arr.splice(opIndex - 2, 3, String(result));
  }

  return Number(arr[0]);
}

Time: O(n²), since each pass re-scans and splices the array · Space: O(n)

Optimal — Stack

Push numbers onto a stack. On an operator, pop the top two numbers (in the right order), apply it, and push the result. One pass, no re-scanning.

function evalRPN(tokens) {
  const stack = [];

  for (const token of tokens) {
    if (token === "+" || token === "-" || token === "*" || token === "/") {
      const b = stack.pop();
      const a = stack.pop();
      let result;
      switch (token) {
        case "+": result = a + b; break;
        case "-": result = a - b; break;
        case "*": result = a * b; break;
        case "/": result = Math.trunc(a / b); break;
      }
      stack.push(result);
    } else {
      stack.push(Number(token));
    }
  }

  return stack.pop();
}

Time: O(n) · Space: O(n)