KatInterview

Evaluate Chained Sum Definitions with Error Detection

Trees & GraphsModel answer
HardModel answerTrees & Graphstopological-sortgraphkahn-algorithm

Last updated

Compute the integer value of every variable defined as a sum of literals and other variables, raising distinct errors for duplicate, undefined, or circular definitions.

Resolve a Set of Sum Definitions

A simulation tool stores its settings as a list of text definitions. Each definition gives one name a value written as a sum of one or more terms joined by +. A term is either:

  • a signed 64-bit integer literal such as 5 or -12, or
  • a variable name made of letters, digits, and underscores (case-sensitive).

Write evaluate_equations so that it computes the final integer value of every defined name and returns a dictionary from name to value.

Raise the matching custom exception when the input is invalid:

  • UndefinedVariableError: a right-hand side uses a name that is never defined on the left of any line.
  • CycleError: names depend on each other in a loop (for example A = B + 1 together with B = A).
  • DuplicateDefinitionError: the same name is defined on the left of more than one line.
class UndefinedVariableError(Exception):
    pass

class CycleError(Exception):
    pass

class DuplicateDefinitionError(Exception):
    pass

def evaluate_equations(equations: list[str]) -> dict[str, int]:
    ...

Input

  • equations: a list of strings, each shaped like name = term + term + ... + term. Tokens are separated by whitespace.

Constraints

  • 1 <= len(equations) <= 20,000
  • The total number of terms over all lines is at most 100,000.
  • Every literal lies in [-2^63, 2^63 - 1].
  • The solution must run in O(V + E) time, where V is the number of distinct names and E the number of name references.

Examples

evaluate_equations([
    "speed = base_speed + offset",
    "base_speed = 30",
    "offset = 5 + 3",
    "max_speed = speed + 10",
])
# {"speed": 38, "base_speed": 30, "offset": 8, "max_speed": 48}
evaluate_equations(["x = y + 2", "y = z + 1", "z = x + 4"])
# raises CycleError
evaluate_equations(["foo = bar + 10"])
# raises UndefinedVariableError

What to cover in your answer

Explain your approach, state how you order the errors when several apply at once, discuss edge cases, give the complexity, and provide working code.

Hints

Hint 1

Split each line into a constant part (the sum of its literals) and a list of referenced names. Keep repeated references, since `a = b + b` uses `b` twice.

Hint 2

Treat names as graph nodes with an edge from each dependency to the name that uses it. A name can be computed once all of its references are computed, which is exactly what topological ordering gives you.

Hint 3

Run Kahn's algorithm with in-degree equal to the number of references (with multiplicity). If fewer nodes are processed than were defined, a cycle exists. Check duplicates and undefined names before evaluating, and decide on an error priority.