Variable Assignment Values
MediumGraphs ยท Instacart
Each string in lines defines one variable, such as "x = a + 3 - b": a name, =, then terms joined by + or -. A term is a non-negative integer or a variable name, and lines may use variables defined later.
For each name in queries, return its value as a string. Return "CYCLE" if the variable depends, directly or through other variables, on a cycle of definitions (a variable that uses itself counts). Otherwise return "UNDEFINED" if it depends on a name that no line defines, or is itself undefined. "CYCLE" takes precedence.
Example 1
- Input:
- lines = ["total = base + 5 - fee", "base = 20", "fee = 3"], queries = ["total", "base"]
- Output:
- ["22", "20"]
- Explanation
totalusesbaseandfee, which are defined on later lines: 20 + 5 - 3 = 22.
Example 2
- Input:
- lines = ["a = b + 1", "b = c - a", "d = 4"], queries = ["a", "d", "e"]
- Output:
- ["CYCLE", "4", "UNDEFINED"]
- Explanation
aandbuse each other.cis also undefined, but"CYCLE"wins.
Example 3
- Input:
- lines = ["p = q + r", "q = s + 1", "r = s - 1", "s = 7"], queries = ["p"]
- Output:
- ["14"]
Constraints
1 <= lines.length <= 20000 <= queries.length <= 2000- Names start with a lowercase letter, then contain lowercase letters, digits or underscores, up to 12 characters; each name is defined at most once
- Integers are in
0to10^6, and each line has at most 100 terms; tokens are separated by single spaces