Evaluate dependent variable expressions
Company: Instacart
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Onsite
Overview: This question evaluates a candidate's ability to parse and evaluate assignment expressions, resolve inter-variable dependencies, and detect cycles or unsolvable references.
Constraints
- 1 <= len(assignments) <= 10^4
- Total length of all assignment strings <= 2 * 10^5
- Variable names match [A-Za-z_][A-Za-z0-9_]*
- Expressions contain only integers, variable names, '+', '-', and spaces; no parentheses
- A leading '+' or '-' may appear before any term (number or variable)
- If a variable is assigned multiple times, the last assignment is used
- Return 'ERROR' on cyclic dependencies or undefined variables
Examples
Input:
Expected Output: ERROR
Hints
- Parse assignments into a map from variable name to its expression; let the last occurrence win.
- Use DFS with memoization to evaluate each variable once; keep a 'visiting' set to detect cycles.
- Scan expressions character-by-character: read optional '+'/'-' signs to determine the term's sign, then read either an integer literal or a variable name.