Evaluate an Arithmetic Expression with Parentheses, Unary Minus and Four Operators
Company: Snowflake
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Technical Screen
Overview: Evaluate an arithmetic expression string with non-negative integers, addition, subtraction, multiplication, division truncating toward zero, parentheses and a unary minus. It tests tokenizing, operator precedence, left-to-right evaluation and deeply nested parentheses without eval.
Constraints
- 1 <= len(expression) <= 10^4
- expression contains only digits, '+', '-', '*', '/', '(', ')' and spaces, and it is a valid expression; spaces can appear between tokens but never inside a number
- '-' can be unary only at the very start of the expression or directly after '(' (ignoring spaces); '+' is never unary
- No division by zero occurs
- Every literal and every intermediate result lies between -2^31 and 2^31 - 1, so the result never exceeds 2^31 - 1 and fits in a signed 32-bit integer
- Parentheses can be nested deeply, up to about half the length of the expression
Examples
Input: ('0',)
Expected Output: 0
Explanation: Minimum valid: the single-digit literal 0 evaluates to zero.
Input: ('(7)',)
Expected Output: 7
Explanation: Minimum valid: a single literal wrapped in one pair of parentheses.
Hints
- Parentheses can nest about 5,000 levels deep in a 10^4-character expression. Think about how much state each open group needs and where you keep it.
- Because '*' and '/' bind more tightly than '+' and '-', a minus sign in front of a product or quotient applies to the whole term. Check that 8 - 9 / 2 gives 4.
- Truncation toward zero and floor division disagree whenever exactly one operand is negative: -7 / 2 must be -3, not -4.