




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.
1def evalRPN(tokens):
2    stack = []
3    for token in tokens:
4        if token in '+-*/':
5            b, a = stack.pop(), stack.pop()
6            if token == '+':
7                stack.append(a + b)
8            elif token == '-':
9                stack.append(a - b)
10            elif token == '*':
11                stack.append(a * b)
12            else:
13                stack.append(int(a / b))  # ensure truncating division
14        else:
15            stack.append(int(token))
16    return stack[0]
17The Python solution efficiently evaluates the RPN expression with a list as a stack. It supports integer parsing, error handling, and result storage. Division operation ensures truncation toward zero as per problem requirements.