KatInterview

Process Sequential Variable Assignments

StringsAuto-graded · 18 test cases
EasyAuto-gradedStringsparsingdictionaryexpression-evaluation

Last updated

Tests parsing and evaluating variable assignments in order, handling literals, references, and arithmetic expressions.

You are given a sequence of variable assignments and a target variable name. Each assignment defines a variable as either a number, a reference to a previously defined variable, or an arithmetic expression using addition and subtraction.

Process the assignments in order and return the final value of the target variable.

Input Format

  • assignments: A list of strings, each containing one assignment in the format name = expression
  • target: The name of the variable whose value you need to return

Assignment Rules

Each assignment follows the pattern name = expression, where:

  • The left side is a variable name (lowercase letters followed by zero or more lowercase letters or digits)
  • The right side is an expression containing:
    • Unsigned decimal integers
    • Variable names (referring only to variables defined earlier in the list)
    • The operators + and -
    • Optional spaces around tokens

Expressions are evaluated left to right. For example, a - b + c means (a - b) + c.

Guarantees

  • Each variable is defined exactly once
  • Variables can only reference other variables that appear earlier in the list
  • No cycles or forward references exist
  • The target variable will be defined in the list
  • All intermediate and final values fit within a signed 32-bit integer
  • Results may be negative

Constraints

  • 1 ≤ len(assignments) ≤ 10,000
  • Total input length ≤ 200,000 characters
  • Variable names match the pattern [a-z][a-z0-9]*
  • Integer literals are non-negative and match [0-9]+
  • No unary operators, parentheses, multiplication, or division

Examples

Example 1

Input: process_assignments(['x1=1', 'x2=x1', 'x3=x2+x1', 'x4=x3-5'], 'x4')

Output: -3

Example 2

Input: process_assignments(['a=8', 'b=a', 'c=a', 'd=b-c'], 'd')

Output: 0

Hints

Hint 1

Store computed values in a dictionary as you process each assignment in order

Hint 2

Use a regular expression to tokenize the right-hand side into variable names, numbers, and operators

Hint 3

Evaluate expressions left to right using an accumulator and the last-seen operator