Evaluate an Integer Expression with + - * / and No Parentheses
Company: Glean
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Onsite
Overview: Evaluate an arithmetic expression string containing non-negative integers, plus, minus, times, integer division and spaces, but no parentheses, respecting operator precedence and left-to-right evaluation. Tests single-pass parsing, precedence handling and truncating integer division.
Constraints
- 1 <= len(expression) <= 3 * 10^5
- expression consists of digits, '+', '-', '*', '/' and ' ', and contains at least one integer.
- Every integer literal is between 0 and 2^31 - 1.
- Every intermediate result and the final result are between -2^31 and 2^31 - 1, so the answer fits in a signed 32-bit integer.
- There are no parentheses and no unary operators, the expression is always valid, and division by zero never occurs.
Examples
Input: ('0',)
Expected Output: 0
Explanation: Single one-character literal zero.
Input: ('2147483647',)
Expected Output: 2147483647
Explanation: Single literal at the literal bound 2^31 - 1.
Hints
- A literal can have several digits and spaces carry no meaning, so finish reading a whole number before applying the operator written before it.
- Because `*` and `/` bind tighter than `+` and `-`, a pending `+` or `-` cannot take full effect until every `*` and `/` that immediately follows it has been applied, in left-to-right order.
- Division must discard the fractional part (round toward zero); check what your language's integer division does if a value you divide can be negative.