Skip to content

Evaluate Reverse Polish Notation

You are given an array of strings tokens that represents an arithmetic expression in a Reverse Polish Notation.

Evaluate the expression. Return an integer that represents the value of the expression.

Note that:

  • The valid operators are +, -, *, and /.
  • Each operand may be an integer or another expression.
  • The division between two integers always truncates toward zero.
  • There will not be any division by zero.
  • The input represents a valid arithmetic expression in a reverse polish notation.
  • The answer and all the intermediate calculations can be represented in a 32-bit integer.
Input: tokens = ["2","1","+","3","*"]
Output: 9
Explanation: ((2 + 1) * 3) = 9
Input: tokens = ["4","13","5","/","+"]
Output: 6
Explanation: (4 + (13 / 5)) = 6

Solution

Use a stack to store the numbers. When we encounter an operator, we pop the last two numbers from the stack, perform the operation and push the result back to the stack.

Implementation

function evalRPN(tokens) {
const operators = {
"+": (a, b) => b + a,
"-": (a, b) => b - a,
"/": (a, b) => (b / a) | 0,
"*": (a, b) => b * a,
};
const stack = [];
for (const token of tokens) {
const operator = operators[token];
if (operator) {
const result = operator(stack.pop(), stack.pop());
stack.push(result);
} else {
stack.push(Number(token));
}
}
return stack.pop();
}

Pseudocode

  1. Create a map of operators to their functions.
  2. Create a stack.
  3. Iterate over the tokens.
    • If the token is an operator, pop the last two numbers from the stack, perform the operation and push the result back to the stack.
    • Otherwise, push the number to the stack.
  4. Return the last number from the stack.

Complexity Analysis

  • Time Complexity: O(n) - You need to iterate over all the tokens.
  • Space Complexity: O(n) - In the worst case, you need to store all the tokens in the stack.