Parse and evaluate nested expressions with validation
Company: Uber
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Online Assessment
Overview: This question evaluates a developer's ability to design and implement a robust parser and evaluator for a parenthesized expression language, testing parsing, lexical scoping and variable binding, operator semantics, error detection, and safe integer arithmetic.
Constraints
- length(expr) <= 1e5
- maximum nesting depth <= 1e4
- integer = optional leading '-' then one or more digits
- variable = lowercase letter then zero or more lowercase letters/digits
- sum/prod require k >= 2 subexpressions; set requires exactly 3 args with a variable first
- all intermediate and final values must fit in a 32-bit signed integer; otherwise InvalidExpression
Examples
Input: ("(sum 1 2)",)
Expected Output: 3
Explanation: 1 + 2 = 3.
Input: ("(prod 2 3 4)",)
Expected Output: 24
Explanation: 2 * 3 * 4 = 24; prod accepts more than two args.
Hints
- Tokenize first: emit '(' and ')' as standalone tokens and collapse runs of non-space, non-paren characters into atom tokens. This makes extra/leading/trailing spaces trivial to handle.
- Use recursive descent: parse() reads one expression (atom or compound); parse_compound() reads the operator then dispatches. Validate arity inside each operator branch and require the closing ')'.
- For scoping, pass an immutable copy (or a parent-linked chain) into the body of set so inner bindings shadow outer ones without mutating the caller's scope.
- Guard every add/multiply/literal with a 32-bit range check, and after the top-level parse confirm all tokens were consumed (a trailing token like an unmatched ')' means invalid).