KatInterview

Resolve Variable Assignments with Dependencies

Trees & GraphsModel answer
MediumModel answerTrees & Graphsrecursiongraphsparsing

Last updated

Parse assignment statements and compute a variable's value by recursively resolving dependencies, detecting cycles and undefined references.

You're given a collection of assignment statements where each statement defines a variable in terms of numeric literals, other variables, or arithmetic operations. Your task is to compute the final numeric value of a specified target variable.

Each assignment has the format name = expression, where:

  • name is a valid identifier (letters, digits, underscores; must start with a letter or underscore)
  • expression contains integers, decimals, variable names, and the binary operators + and -
  • Unary minus is allowed (e.g., -x or 3 - -2)
  • No parentheses, multiplication, or division

Requirements:

  1. Compute the numeric value of the target variable by resolving all dependencies
  2. Detect and report cycles (e.g., A = B + 1 and B = A would form a cycle)
  3. Detect and report undefined variable references
  4. Detect and report duplicate definitions of the same variable
  5. Handle malformed syntax gracefully with clear error messages

Example:

Given assignments ["X = 10", "Y = X + 5", "Z = Y - X"] and target "Z":

  • X evaluates to 10
  • Y evaluates to 10 + 5 = 15
  • Z evaluates to 15 - 10 = 5

Return 5.

What to provide:

  • Your approach to modeling and solving this problem
  • How you handle cycles and missing variables
  • Time and space complexity analysis
  • Working code in Python

Hints

Hint 1

Think of assignments as forming a directed graph where edges represent dependencies between variables

Hint 2

Use depth-first search with three states: unvisited, currently visiting (on stack), and fully evaluated

Hint 3

Memoization prevents recomputing shared dependencies and keeps complexity linear