KatInterview

Resolve Out-of-Order Variable Assignments in a Mini Language

Trees & GraphsModel answer
MediumModel answerTrees & Graphstopological-sortparsingdependency-graph

Last updated

Parse lines of integer assignments using only + and -, resolve forward and chained references, and report undefined names and cycles in a well-defined way.

Problem

You are given the source of a tiny scripting language. Each non-empty line is a single assignment:

<name> = <expression>
  • <name> matches [a-zA-Z_][a-zA-Z0-9_]*.
  • <expression> is a chain of non-negative integer literals and variable names joined by + and -.
  • There are no parentheses, and operators are applied strictly left to right.
  • Whitespace may appear anywhere, or nowhere, and carries no meaning. foo=bar+5-baz and foo = bar + 5 - baz are the same statement.
  • All values are integers.

A variable may refer to variables assigned earlier or later in the text, and references can form long chains (a uses b, b uses c, and so on).

Task

Implement:

evaluate(program: string) -> Map<string, int>

It returns the final integer value of every variable in the program.

Examples

foo = bar + 5
bar = 2

gives { "bar": 2, "foo": 7 }.

foo = bar + 1
bar = baz + 1
baz = 3

gives { "baz": 3, "bar": 4, "foo": 5 }.

Error situations you must handle

  1. Undefined variable. An expression uses a name that is never assigned anywhere. The user of that name cannot be evaluated.
  2. Cyclic dependency. For example foo = bar + 1 and bar = foo + 1. None of the variables involved can be evaluated.
  3. Partial results. In
    ok = 1
    bad = missing + 1
    
    ok is fine but bad is not. Choose one policy and document it: either (a) fail the entire call if any variable is invalid, or (b) return everything that could be evaluated and report the rest separately.

Constraints

With N variables and M total tokens in all expressions, aim for O(N + M) time and space. Assume N and M can be large, so think about stack depth for long dependency chains.

What to deliver

  • Working code in a language of your choice.
  • A short explanation of how you represent the dependency graph, in what order you evaluate, how you detect undefined names and cycles, and the time and space complexity.

Hints

Hint 1

Separate the work into parsing (turning each line into a name plus a list of signed terms) and evaluation (deciding the order in which variables can be computed).

Hint 2

Treat 'x uses y' as an edge y -> x. A variable is ready once all variables it uses have values, which is exactly the situation topological sorting with in-degrees (Kahn's algorithm) handles iteratively.

Hint 3

Anything that never reaches in-degree zero is on a cycle or depends on one, and a reference to a name with no assignment can be flagged while building the graph. Deduplicate dependencies per variable so that `a = b + b` does not inflate the in-degree.