Katkat

Evaluate Ordered Variable Definitions with Addition and Subtraction

InstacartSoftware Engineer · Onsite

Last updated

Evaluate ordered variable definitions and plus/minus expressions with an explicit directional grammar, while distinguishing assignment lookup from general equation solving.

Evaluate a requested variable from an ordered list of definitions. A definition may be a number, a reference to an earlier variable, or an expression containing addition and subtraction.

Implement evaluate_definitions(definitions: string[], target: string) -> int.

Constraints & Assumptions

The report emphasizes an implicit directional and ordered-definition assumption. This practice contract makes it explicit: every variable is defined exactly once, and every reference on a right-hand side refers to an earlier definition. Definitions are assignments, not symmetric equations to solve. There are no cycles, forward references, or multiple definitions.

  • Between 1 and 10000 definitions; target is defined.
  • Variable names match [a-z][a-z0-9]*.
  • Grammar: name = term ((+|-) term)*; a term is a variable name or an unsigned decimal integer. Optional ASCII spaces may surround tokens. Unary signs, parentheses, multiplication, and division are excluded.
  • Terms are evaluated left to right. Literal values, intermediate results, and final results fit signed 32-bit integers; negative results are allowed.
  • Total input length is at most 200000 characters.

The first reported part permits one term per definition. The full function also handles the reported plus/minus extension.

Examples

definitions = ["x1=1","x2=x1","x3=x2+x1","x4=x3-5"]
target = "x4"
result = -3
definitions = ["a=8","b=a","c=a","d=b-c"]
target = "d"
result = 0

Explain why a symbol table is sufficient under this contract and why input such as x1=x2; x1=1; query x2 violates it. Discuss how forward references, conflicting assignments, or truly symmetric equations would change the problem before choosing a different data structure.

Hints

Hint 1

Direction matters: A definition gives a value to its left-hand name. The ordering guarantee tells you whether every referenced value is already available.