Drill

ProblemsJavaScript › patterns

Evaluate a postfix expression

mediumpatternsStacksParsingJavaScript

A tiny expression engine accepts a calculation already written in postfix — operands first, operator after — and works it out.

evaluatePostfix(tokens: list<string>) → int

Solve it in the editor →

Where you start

function evaluatePostfix(tokens) {
  
}

Worked examples

CallResult
evaluatePostfix(["3","4","+"])7
evaluatePostfix(["10","3","-"])7
evaluatePostfix(["2","3","*","4","+"])10
evaluatePostfix(["12","4","/"])3

Hint

One stack. Push numbers; when an operator arrives, pop two, apply it, push the result back.

Reference solution in JavaScript
function evaluatePostfix(tokens) {
  const stack = [];
  for (const tok of tokens) {
    if (tok.length > 1 || (tok >= '0' && tok <= '9')) {
      stack.push(Number(tok));
    } else {
      const b = stack.pop();
      const a = stack.pop();
      if (tok === '+') stack.push(a + b);
      else if (tok === '-') stack.push(a - b);
      else if (tok === '*') stack.push(a * b);
      else stack.push(Math.trunc(a / b));
    }
  }
  return stack.length ? stack.pop() : 0;
}

The same problem in another language

More patterns problems in JavaScript