Evaluate arithmetic expression with precedence
InstacartSoftware Engineer · OnsiteLast updated
Instacart software-engineer onsite coding question: implement an arithmetic expression evaluator for a string of non-negative integers, +, -, *, /, parentheses, and spaces. It tests operator precedence and associativity, unary minus, 64-bit intermediates, integer division truncating toward zero, and robust handling of invalid input via a two-stack, shunting-yard, or recursive-descent parser.
Question
Implement an evaluator for a string arithmetic expression. The input contains non-negative integers, the operators +, -, *, /, parentheses ( and ), and arbitrary spaces. Your evaluator must respect operator precedence (* and / bind tighter than + and -) and left-to-right associativity, and return the result as a 64-bit integer.
- Core evaluation. Parse and evaluate the expression, honoring precedence, associativity, and parentheses. Use 64-bit intermediate values to avoid overflow on large sub-results.
- Unary minus. Support a leading or post-operator unary minus, e.g.
-3+5,2*-4, or-(1+2). - Integer division. Division is integer division that truncates toward zero (so
7/2 == 3and-7/2 == -3). - Error handling. Return an error (or raise) for invalid input such as mismatched parentheses, an empty/garbage token stream, or division by zero.
- Approach and complexity. Describe your method (e.g. the two-stack operator/operand technique, the shunting-yard algorithm, or a recursive-descent parser), and analyze its time and space complexity. Aim for O(n) time and O(n) space, where n is the length of the input string.
Example: "2*(3+ -4) / 2" evaluates to -1.
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.