30 March 2024

Medium

150. Evaluate Reverse Polish Notation

Link: https://leetcode.com/problems/evaluate-reverse-polish-notation

Description: Evaluate the value of an arithmetic expression in Reverse Polish Notation.

Solution:

Create a stack to store the operands. Iterate through the tokens and push numbers onto the stack. When an operator is encountered, pop the last two elements from the stack, perform the operation, and push the result back onto the stack. Finally, return the last element from the stack.

/**
 * @param {string[]} tokens
 * @return {number}
 */
var evalRPN = function (tokens) {
  const stack = []

  const operators = ['+', '-', '*', '/']

  for (let t of tokens) {
    if (!operators.includes(t)) {
      stack.push(+t)
    } else {
      const right = stack.pop()
      const left = stack.pop()
      if (t === '+') {
        stack.push(left + right)
      } else if (t === '-') {
        stack.push(left - right)
      } else if (t === '*') {
        stack.push(left * right)
      } else if (t === '/') {
        stack.push(Math.trunc(left / right))
      }
    }
  }

  return stack.pop()
}