Evaluate a Four-Operator Expression
Company: DoorDash
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: easy
Interview Round: Onsite
Quick Answer: This question evaluates expression-evaluation skills such as operator precedence, integer arithmetic semantics (truncating division), and string parsing/tokenization.
Constraints
- 1 <= len(s) <= 200000
- `s` contains only digits, spaces, and the operators `+`, `-`, `*`, `/`.
- The expression is always valid and contains no parentheses.
- All integer literals are non-negative.
- Division by zero will not occur.
- The final answer fits in a signed 32-bit integer.
Examples
Input: ("3+2*2",)
Expected Output: 7
Explanation: Multiplication is evaluated first: 2 * 2 = 4, then 3 + 4 = 7.
Input: (" 14 - 3 / 2 ",)
Expected Output: 13
Explanation: 3 / 2 truncates to 1, so the expression becomes 14 - 1 = 13.
Input: ("18/3*2+5",)
Expected Output: 17
Explanation: Division and multiplication have the same precedence and are evaluated left to right: 18 / 3 = 6, 6 * 2 = 12, then 12 + 5 = 17.
Input: ("42",)
Expected Output: 42
Explanation: A single number evaluates to itself.
Input: ("0-3/2",)
Expected Output: -1
Explanation: The subtraction creates a negative term: -3 / 2 truncates toward zero to -1.
Input: ("1+2*3-4/5+6",)
Expected Output: 13
Explanation: 2 * 3 = 6 and 4 / 5 truncates to 0, so the expression becomes 1 + 6 - 0 + 6 = 13.
Input: (" 100000 / 10 / 3 ",)
Expected Output: 3333
Explanation: Division is evaluated left to right: 100000 / 10 = 10000, then 10000 / 3 truncates to 3333.
Hints
- When you finish reading a number, apply the previous operator to it rather than the current operator.
- To handle precedence without parentheses, keep track of the most recent multiplication/division term separately from the committed addition/subtraction total.