Evaluate arithmetic expression without parentheses
Company: Meta
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Onsite
Quick Answer: Evaluate arithmetic expression without parentheses evaluates algorithm design, data structures, correctness, complexity, edge cases, and implementation details in a realistic interview setting. A strong answer states assumptions, handles edge cases, explains trade-offs, and shows how to validate the result clearly.
Constraints
- 1 <= len(s); the expression is non-empty and represents a valid expression.
- s contains only digits, '+', '-', '*', '/', and ' ' (space).
- All integers in the expression are non-negative; intermediate and final results fit in a 32-bit signed integer.
- Integer division truncates toward zero (3/2 == 1, and would give -1 for a negative quotient).
- No parentheses; the input has a number after every operator (trailing operators are invalid and out of scope).
Examples
Input: ("3+2*2",)
Expected Output: 7
Explanation: * binds tighter: 2*2=4, then 3+4=7.
Input: (" 3/2 ",)
Expected Output: 1
Explanation: Leading/trailing spaces ignored; 3/2 truncates toward zero to 1.
Hints
- Walk the string once. Build the current number digit by digit (num = num*10 + digit) so multi-digit numbers and runs of spaces are handled naturally.
- Remember the operator that came BEFORE the current number. Only act when you hit the next operator (or the final character): that's when the pending number is complete.
- Defer + and - by pushing the signed number onto a stack; apply * and / immediately to the top of the stack. The final answer is the sum of the stack — precedence is handled for free.
- For truncate-toward-zero division, use int(a / b) in Python (Python's // floors, which differs for negatives). Java, C++, and JS Math.trunc already truncate toward zero.