Evaluate an arithmetic expression
Company: Instacart
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Technical Screen
Quick Answer: This question evaluates a candidate's ability to implement expression parsing and evaluation, assessing competencies in string parsing, operator precedence, parentheses handling, and integer arithmetic semantics including truncation toward zero.
Constraints
- 1 <= len(s) <= 100000
- s contains digits, spaces, '+', '-', '*', '/', '(', and ')'
- All numbers in the expression are non-negative integers
- The expression is valid and division by zero will not occur
- The final result fits in a 32-bit signed integer
Examples
Input: "3+2*2"
Expected Output: 7
Explanation: Multiplication happens first: 2*2 = 4, then 3+4 = 7.
Input: " 3/2 "
Expected Output: 1
Explanation: 3 divided by 2 truncates toward zero, so the result is 1.
Input: " 3+5 / 2 "
Expected Output: 5
Explanation: 5/2 = 2 after truncation, then 3+2 = 5.
Input: "2*(3+(4-1))"
Expected Output: 12
Explanation: Inside the parentheses, 4-1 = 3, then 3+3 = 6, and finally 2*6 = 12.
Input: "42"
Expected Output: 42
Explanation: A single number evaluates to itself.