Problem Description
Given an array of strings representing an arithmetic expression in Reverse Polish Notation (RPN), evaluate the expression and return the resulting integer. The valid operators are "+", "-", "*", and "/". The division between two integers should truncate toward zero. The input is guaranteed to be a valid RPN expression.
Key Insights
- Use a stack to process the tokens.
- Push numbers onto the stack.
- When an operator is encountered, pop the top two numbers, perform the operation, and push the result back.
- Handle division carefully to ensure it truncates toward zero.
- The final result remains as the only value in the stack.
Space and Time Complexity
Time Complexity: O(n), where n is the number of tokens (each token is processed once). Space Complexity: O(n), in the worst-case scenario where all tokens are numbers and are stored in the stack.
Solution
We use a stack data structure to evaluate the RPN expression. Iterate through each token:
- If the token is a number, convert and push it onto the stack.
- If the token is an operator, pop the top two numbers (be careful about order), perform the corresponding arithmetic operation, and push the result back onto the stack.
- At the end of processing, the stack contains the result of the expression. Special attention is needed for division to ensure it truncates toward zero (using language-specific functions when necessary).