




Sponsored
Sponsored
The stack-based approach is ideal for evaluating Reverse Polish Notation (RPN) expressions because it naturally follows the Last-In-First-Out (LIFO) principle, which aligns with the evaluation order of RPN expressions. The key idea is to iterate through the tokens, pushing operands onto the stack, and handling operators by popping the required number of operands from the stack, performing the operation, and pushing the result back onto the stack.
Time Complexity: O(n), where n is the number of tokens.
Space Complexity: O(n) due to stack usage.
1function evalRPN(tokens) {
2    const stack = [];
3    for (const token of tokens) {
4        if ('+-*/'.includes(token)) {
5            const b = stack.pop();
6            const a = stack.pop();
7            switch (token) {
8                case '+': stack.push(a + b); break;
9                case '-': stack.push(a - b); break;
10                case '*': stack.push(a * b); break;
11                case '/': stack.push(Math.trunc(a / b)); break;
12            }
13        } else {
14            stack.push(parseInt(token));
15        }
16    }
17    return stack.pop();
18}
19JavaScript solution applies a stack-based approach using an array. It efficiently handles input parsing and arithmetic operation execution, utilizing language-specific string and math functions to comply with evaluation requirements.