Implement basic expression evaluator
Company: Meta
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: Medium
Interview Round: Onsite
Quick Answer: This question evaluates proficiency in expression parsing, operator precedence handling, integer arithmetic semantics (including truncating division), and efficient tokenization and evaluation within the Coding & Algorithms domain.
Constraints
- 1 <= s.length <= 3 * 10^5
- s consists of non-negative integers and the characters '+', '-', '*', '/', and ' '.
- s represents a valid expression.
- All intermediate values fit in a signed 32-bit integer.
- The integer division truncates toward zero.
- Parentheses are not allowed; do not use any built-in eval.
Examples
Input: "3+2*2"
Expected Output: 7
Explanation: 2*2=4 binds tighter than +, so 3+4=7.
Input: " 3/2 "
Expected Output: 1
Explanation: Spaces are ignored; 3/2 truncates to 1.
Input: " 3+5 / 2 "
Expected Output: 5
Explanation: 5/2=2 first, then 3+2=5.
Input: "14-3/2"
Expected Output: 13
Explanation: 3/2=1, then 14-1=13.
Input: "100"
Expected Output: 100
Explanation: A single number evaluates to itself.
Input: "2*3*4"
Expected Output: 24
Explanation: Left-to-right multiplication: (2*3)*4=24.
Input: "10-2*3+4/2"
Expected Output: 6
Explanation: 2*3=6 and 4/2=2, then 10-6+2=6.
Input: "0"
Expected Output: 0
Explanation: Boundary: zero.
Input: "1+1+1+1"
Expected Output: 4
Explanation: Pure addition stresses the stack worst case.
Input: "7/3"
Expected Output: 2
Explanation: 7/3=2.33 truncates toward zero to 2.
Hints
- Track a running operator (start as '+') and accumulate the current number digit by digit. Apply the operator when you hit the next operator or the end of the string.
- Use a stack: for '+' push +num, for '-' push -num. For '*' and '/', pop the top value and combine immediately — that resolves the higher precedence on the fly.
- The final answer is just the sum of everything left on the stack — no second pass needed.
- For truncate-toward-zero division with negatives on the stack, divide magnitudes and re-apply the sign (Python's // floors, so handle the sign explicitly).