Evaluate Formulas with Cycle Detection
Problem statement
You are given an array formulas of variable assignments and the name target. Each assignment has the form name = operand or name = operand + operand - operand .... An operand is an integer literal or another variable. References may point forward or backward. Evaluate the requested variable and return its value as a decimal string. Return the empty string if its value cannot be determined.
For this exercise, use the following rules. Tokens are separated by exactly one ASCII space. Names are case-sensitive, start with an ASCII letter, and may then contain ASCII letters or digits. Addition and subtraction are evaluated from left to right, with no parentheses or other operators.
- Only the target and variables reachable through its definitions affect the answer. An undefined variable, dependency cycle, or conflicting definitions in that dependency closure makes the answer empty. Errors in unrelated variables are ignored.
- A variable may have several assignments. Evaluate every right-hand side; they must all produce the same integer. Different values are a conflict. Equivalent expressions and repeated identical assignments are allowed.
- Every reference in every relevant definition is a dependency, even when arithmetic could cancel it. A cycle is rejected; do not solve a system of simultaneous equations or discard a cyclic alternative definition.
- All literals and all intermediate and final values of evaluable expressions fit in a signed 64-bit integer. Return a canonical decimal string without leading zeros, or exactly
""on failure.
The single-operand case is the base exercise; expressions and error handling are cumulative follow-ups.
Function
evaluateFormulas(formulas: String[], target: String) → StringExamples
Example 1
formulas = ["T1 = T2","T2 = 7","answer = T1 + 3 - 2"]target = "answer"return = "8"The reference chain gives T1 = T2 = 7, so answer = 7 + 3 - 2 = 8.
Example 2
formulas = ["x = y + 1","y = x - 1"]target = "x"return = ""The reachable definitions form a cycle. They are not solved as simultaneous equations.
Example 3
formulas = ["a = 5","a = b + 1","b = 4","target = a - 2","unused = missing"]target = "target"return = "3"Both definitions of a evaluate to 5. The unrelated missing reference is ignored, so target = 3.
Constraints
0 <= formulas.length <= 100000.- Each assignment is syntactically valid and contains an ASCII-letter-first name, a separated
=token, and one or more operands alternating with separated+or-tokens. Names may contain ASCII letters and digits. targetis a valid name. Definitions and references need not be unique or complete.- The total number of space-separated tokens across all formulas is at most
500000; the total input text contains at most5000000characters. - Integer literals are decimal digits with an optional leading minus sign. Every literal, intermediate value, and result of an evaluable expression fits in a signed 64-bit integer.