Skip to problem
←

Evaluation of Postfix Expression

Easy 0 attempts

You're given an arithmetic expression exp written in postfix form. Evaluate it and return the final result, supporting the operators +, -, *, and /. Operands are single digits (0 through 9) and the expression has no separators. Division truncates toward zero. The expression is valid and never divides by zero.

Function contract

exp is a valid postfix string containing only single digits 0–9 and the operators +, -, *, /, without spaces.

Output: Return the integer result, truncating each division toward zero.

Example 1

Input
exp = "231*+9-"
Output
-4

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

Example 2

Input
exp = "82/"
Output
4
Constraints
  • 1 <= length of expression <= 100
  • 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-Based Evaluation

This version uses single-digit operands with no separators. Pop the right operand before the left; division truncates toward zero.

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

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

Loading discussion…

Saved in this browser only. Private to you.

JavaScript