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.
Input: (" 3+5 / 2 ",)
Expected Output: 5
Explanation: 5/2=2 first, then 3+2=5; interior spaces around the operator are skipped.
Input: ("14-3/2",)
Expected Output: 13
Explanation: 3/2=1 (truncated), then 14-1=13.
Input: ("42",)
Expected Output: 42
Explanation: A single multi-digit number with no operator.
Input: ("1-1+1",)
Expected Output: 1
Explanation: Left-to-right for equal-precedence + and -: 1-1=0, 0+1=1.
Input: ("0",)
Expected Output: 0
Explanation: Zero edge case.
Input: ("100*2/25",)
Expected Output: 8
Explanation: Chained * and /: 100*2=200, 200/25=8.
Input: ("2-3*4",)
Expected Output: -10
Explanation: 3*4=12, then 2-12=-10 — negative intermediate result is fine.
Input: (" 30 ",)
Expected Output: 30
Explanation: Multiple leading and trailing spaces around a single number.
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.