KatInterview

Resolve Variable Dependencies with Arithmetic

Trees & GraphsAuto-graded · 23 test cases
MediumAuto-gradedTrees & Graphsrecursiongraph-traversalcycle-detection

Last updated

Tests dependency graph traversal, cycle detection, and recursive evaluation of variables defined by arithmetic expressions.

You are given a target variable name and a list of variable assignments. Each assignment defines a variable in terms of:

  • An integer literal (e.g., "X=5"),
  • Another variable (e.g., "X=Y"), or
  • An arithmetic expression with exactly one + or - operator between two operands (e.g., "X=Y+Z" or "X=A-B"), where each operand is either an integer literal or a variable name.

Your task is to compute the numeric value of the target variable by resolving all dependencies.

If the dependency graph contains a cycle (a variable's value depends on itself, directly or indirectly), or if any required variable is undefined, return the string "IMPOSSIBLE".

Details:

  • Variable names and integer literals may contain negative signs. A leading - in an expression like "X=-5" represents a negative literal, not an operator.
  • Operators (+ or -) appear at position 1 or later in the right-hand side, so "X=-3" is interpreted as assigning -3 to X, not as X = (nothing) - 3.
  • Whitespace in assignments may be present and should be ignored.
  • If a variable is assigned multiple times, use the last assignment.

Constraints:

  • 1 ≤ number of assignments ≤ 1000
  • Variable names are non-empty strings
  • Integer values fit within standard 32-bit signed integer range
  • Each arithmetic expression contains at most one operator
  • The target variable is a non-empty string

Examples

Example 1

Input: resolve_variable('T3', ['T1=1', 'T2=2', 'T3=T4', 'T4=T5', 'T5=T2'])

Output: 2

Example 2

Input: resolve_variable('T3', ['T1=7', 'T2=4', 'T3=T1+T2'])

Output: 11

Example 3

Input: resolve_variable('T4', ['T4=T5', 'T5=T4'])

Output: 'IMPOSSIBLE'

Hints

Hint 1

Model the assignments as a directed graph where each variable points to the variables it depends on.

Hint 2

Use depth-first search with three states (unvisited, visiting, visited) to detect cycles during traversal.

Hint 3

Parse each right-hand side by scanning for the first + or - operator starting from index 1 to handle negative literals correctly.