KatInterview

Evaluate Variable Expressions with Dependencies

Trees & GraphsAuto-graded · 19 test cases
MediumAuto-gradedTrees & Graphstrees-graphsstacks-queuestopological-sort

Last updated

Evaluate symbolic variable definitions with standard arithmetic precedence, resolving variable dependencies while detecting cycles and missing definitions.

You are given a dictionary expressions where each key is a variable identifier and each value is an arithmetic expression string.

An expression string consists of:

  • Non-negative integer literals (e.g., "42")
  • Variable identifiers referencing other keys in expressions
  • Binary operators: +, -, and *
  • Single space delimiters between tokens

Your task is to calculate and return a dictionary mapping every variable to its fully evaluated integer value.

Processing Rules

  1. Operator Precedence: Operators follow standard math precedence (* evaluates before + and -). Operators of identical precedence evaluate left-to-right.
  2. Dependency Resolution: A variable can reference other variables in its expression. Each variable must be evaluated after all variables it depends on have been calculated.
  3. Validation & Errors:
    • If an expression references a variable identifier that does not exist in expressions, raise a ValueError with the message: "Undefined variable: <name>" (where <name> is the name of the missing variable).
    • If a circular dependency exists among the variable definitions (e.g., x references y and y references x), raise a ValueError with the exact message: "Circular dependency detected".

Constraints

  • 1 <= len(expressions) <= 10^4
  • Variable identifiers consist of letters, digits, and underscores.
  • Each expression string contains between 1 and 200 characters.
  • Operands and operators are strictly separated by single spaces.
  • Intermediate and final values fit within standard signed 64-bit integers.

Examples

Example 1

Input: evaluate_expressions({'A': '3 + 2', 'B': 'A * 4', 'C': 'B - 2 + A'})

Output: {'A': 5, 'B': 20, 'C': 23}

Hints

Hint 1

Model the variables as nodes in a graph where directed edges point from a variable to its referenced dependencies.

Hint 2

Use a 3-state graph traversal (Unvisited, Visiting, Visited) to perform topological sorting and detect cycles along the path.

Hint 3

Because expressions lack parentheses, you can compute them in a single linear scan maintaining a running total and a current term for multiplication precedence.