Implement an Arithmetic Expression Evaluator
Company: Otter.Ai
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Technical Screen
Quick Answer: This question evaluates expression parsing, operator precedence, tokenization, integer arithmetic semantics (including truncation), and handling of nested parentheses within the Coding & Algorithms domain.
Part 1: Evaluate Arithmetic Expressions Without Parentheses
Constraints
- 1 <= len(expression) <= 100000
- The expression contains digits, spaces, '+', '-', '*', and '/' only
- The expression is syntactically valid
- All numbers in the expression are non-negative integers
- Division by zero will not occur
- The final result fits in a 32-bit signed integer
Examples
Input: "3+2*2"
Expected Output:
Explanation: Multiplication happens before addition: 3 + (2 * 2) = 7.
Input: " 3/2 "
Expected Output:
Explanation: Integer division truncates toward zero, so 3 / 2 = 1.
Input: " 3+5 / 2 "
Expected Output:
Explanation: 5 / 2 = 2, then 3 + 2 = 5.
Input: "42"
Expected Output:
Explanation: Edge case: a single number with no operators.
Input: "14-3/2"
Expected Output:
Explanation: 3 / 2 = 1, then 14 - 1 = 13.
Hints
- Process the string from left to right while keeping track of the previous operator and the current number.
- You do not need a full parser here: handle '+' and '-' by committing the previous term, and handle '*' and '/' immediately on the most recent term.
Part 2: Evaluate Arithmetic Expressions With Nested Parentheses
Constraints
- 1 <= len(expression) <= 100000
- The expression contains digits, spaces, '+', '-', '*', '/', '(', and ')' only
- The expression is syntactically valid
- All numbers written in the expression are non-negative integers
- Division by zero will not occur
- The final result fits in a 32-bit signed integer
Examples
Input: "(2+6*3+5-(3*14/7+2)*5)+3"
Expected Output:
Explanation: This is the sample with nested parentheses and mixed operators.
Input: "(2 + 3) * (4 - 1)"
Expected Output:
Explanation: Each parenthesized group is evaluated first: 5 * 3 = 15.
Input: "2*(5+5*2)/3+(6/2+8)"
Expected Output:
Explanation: Evaluate parentheses first, then apply operator precedence with truncating division.
Input: "7"
Expected Output:
Explanation: Edge case: a single number without any operators or parentheses.
Input: "((1))"
Expected Output:
Explanation: Edge case: deeply nested parentheses around a single value.
Hints
- A recursive helper can evaluate one parenthesized subexpression and return both its value and the position where it ends.
- Inside each recursive call, you can reuse the same precedence-handling idea from Part 1.