Evaluation of Postfix Expression Easy 0 attempts
GeeksforGeeks ↗

Evaluation of Postfix Expression

Easy Stack&Queue GeeksforGeeks

Given a postfix expression, evaluate it and return the result. Supported operators: +, -, *, /.

Example: exp = "231*+9-" → Output: -4 (2+3*1-9)

Sample Input
Sample Output
Constraints
  • 1 <= length of expression <= 100
Test Cases
Case 1
Args: ["231*+9-"] Expected: -4
Topics

Stack-Based Evaluation

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)

Saved in this browser only. Private to you.

JavaScript