Problem Description
Given a valid arithmetic expression as a string that includes non-negative integers and the operators '+', '-', '*', and '/'. Evaluate the expression while respecting the operator precedence (multiplication and division have higher precedence than addition and subtraction). The division should truncate toward zero. The expression is guaranteed to be valid, and the answer will fit in a 32-bit integer.
Key Insights
- The expression can be processed in one pass while using a stack to handle operator precedence.
- When encountering '+' or '-' operators, the current number is directly added or subtracted (as a positive or negative value).
- For '*' and '/' operators, compute immediately with the last number from the stack and update it.
- Handle spaces and multi-digit numbers by building the number while iterating over the string.
- Division truncation toward zero must be carefully applied, which aligns with typical integer division in most languages.
Space and Time Complexity
Time Complexity: O(n) where n is the length of the expression, since the algorithm processes each character once.
Space Complexity: O(n) in the worst-case scenario when all numbers are stored in the stack.
Solution
We use a stack-based approach. Iterate over each character of the string while maintaining a variable for the current number and a previous operator (initialized to '+'). When an operator or the end of the string is reached, perform an action based on the previous operator:
- For '+' add the current number to the stack.
- For '-' add the negative of the current number.
- For '*' and '/' pop the last number from the stack, compute the result by performing multiplication or division, and then push the result back to the stack. After processing the entire string, sum the elements in the stack to get the final result. This approach ensures that multiplication and division are handled before addition and subtraction.