Incremental Config Value Store with Dependency Tracking
Data Structure DesignAuto-graded · 13 test casesLast updated
Tests ability to build a stateful key-value store that resolves integer expressions with named references, propagates updates through a dependency graph, and rejects cycles.
You are building an in-memory store for a configuration system. Values in the store can be plain integers or expressions that sum up integer literals and references to other stored names. Implement the function described below in three stages, making sure each stage is correct before building on it.
The store exposes two operations, driven by a list of operation names and their corresponding arguments:
set_var(name, value)— defines or redefines a named entry.get_var(name)— retrieves the current resolved integer for a name, orNone.
The function receives a sequence of such operations and returns one result per operation in the same order. set_var results are None on success and the string "ValueError" when a definition is rejected (see Part 3). get_var results are the resolved integer or None.
Part 1 — Integer entries only
set_var(name, value) stores a plain Python int. get_var(name) returns it, or None if name has never been set. Choose internal storage that you will not need to throw away when expressions arrive in Part 2.
Complexity: set_var O(1), get_var O(1).
Part 2 — Expression entries, full recompute
set_var now also accepts a string that begins with =. Everything after the = is a sum of terms separated by +, where each term is either a plain integer literal or the name of another entry — for example "=base+retry+2".
get_var returns the computed sum. If any name referenced directly or transitively by an expression has never been set, get_var returns None for that expression and for anything that depends on it. You may assume no cycles exist in this stage.
Recomputing every entry from scratch on every set_var call is acceptable here, so that get_var stays O(1) by reading a cached result.
Complexity: set_var O(total size of all expressions), get_var O(1).
Part 3 — Cycle rejection and targeted recompute
Two additional requirements apply:
-
Cycle rejection. Before accepting a new definition for a name, check whether that definition would introduce a cycle (directly or transitively). If it would, do not modify any existing state and instead record
"ValueError"as the result for that operation. -
Targeted recompute. After a successful
set_var, recompute only the changed entry and the entries that transitively depend on it — not every entry in the store.
Complexity: set_var O(size of affected downstream subgraph), get_var O(1).
Constraints
- Name strings are valid identifiers (letters, digits, underscores; do not start with a digit), case-sensitive.
- Integer literals in expressions and plain integer values may be negative or zero; no guaranteed range beyond standard Python integers.
- A name may be redefined any number of times, including switching between a plain integer and an expression.
- Expression terms are separated solely by
+; no spaces, no other operators. - Each term in an expression is either a valid identifier or a decimal integer (possibly with a leading
-). get_varon a name that was never set returnsNone.get_varon an expression whose dependency chain includes any never-set name returnsNone.- Cycles will not appear in the input during Parts 1 and 2; in Part 3 they must be detected and rejected as described.
1 ≤ len(operations) = len(arguments) ≤ 1000.- Each expression contains at most 50 terms.
- At most 200 distinct names will be stored.
Examples
Example 1
Input: run_config_store(['set_var', 'set_var', 'set_var', 'get_var', 'set_var', 'get_var', 'get_var'], [['base_timeout', 5], ['retry_timeout', '=base_timeout+10'], ['total_budget', '=retry_timeout+base_timeout+1'], ['total_budget'], ['base_timeout', 8], ['retry_timeout'], ['total_budget']])
Output: [None, None, None, 21, None, 18, 27]
Example 2
Input: run_config_store(['set_var', 'set_var', 'get_var', 'set_var', 'get_var'], [['a', '=missing+2'], ['b', '=a+3'], ['b'], ['missing', 4], ['b']])
Output: [None, None, None, None, 9]
Example 3
Input: run_config_store(['set_var', 'set_var', 'set_var', 'get_var'], [['a', 1], ['b', '=a+2'], ['a', '=b+1'], ['b']])
Output: [None, None, 'ValueError', 3]
Hints
Hint 1
For Part 2, a memoized recursive evaluator naturally processes dependencies before the variable that depends on them — you get a correct evaluation order without an explicit topological sort.
Hint 2
For cycle detection in Part 3, walk the *existing* dependency graph starting from the new definition's referenced names before touching any stored state; if you reach the name being defined, reject the call.
Hint 3
To do a targeted recompute efficiently, maintain two edge directions: deps[name] (what a name reads from) and dependents[name] (what reads from a name). When a name changes, walk forward through dependents to find all affected entries, then evaluate them in an order where each entry is computed after the entries it reads from.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The function simulates a stateful store across all operations in order, maintaining three internal maps: a definitions map from name to parsed definition, a values map of cached resolved integers, and a dependents map tracking which names directly reference each name.
Parsing
An expression string like "=base+retry+2" is split on + after stripping the leading =. Each piece is classified as an integer literal or a name reference. Plain integer arguments produce a ("literal", value) definition. This structure is the same regardless of stage, so it never needs to be replaced.
Part 1 (literals only)
set_var stores a ("literal", value) definition and writes the integer directly to values. get_var reads from values, returning None if the key is absent. Both are O(1).
Part 2 (expression entries, full recompute)
A memoized recursive evaluate function processes each name: if it is a literal, return the integer; if it is an expression, recursively evaluate every referenced name first. Memoisation means each name is evaluated at most once per recompute pass, so the total cost is O(sum of all expression sizes). Calling set_var triggers a full recompute of every defined name, after which all cached values are up to date and get_var is O(1). Any name that is never defined evaluates to None, and anything that transitively depends on it also evaluates to None.
Part 3 (cycle rejection + targeted recompute)
Cycle detection happens before any state change. Starting from the new definition's direct dependencies, a DFS walks the existing dependency graph. If it ever reaches the name being defined, the new definition would form a cycle: record "ValueError" and skip all mutations. Because no state is mutated, a rejected call leaves the store exactly as it was.
Targeted recompute is correct and efficient because only entries that can possibly have changed are touched. After committing the new definition and updating the deps/dependents edges, a forward BFS through dependents collects every transitively affected name. Those names are then evaluated using the same memoized recursive evaluator, but entries outside the affected set are read from the existing values cache without recomputation. Finally, values is updated only for the affected entries.
Evaluation order is guaranteed by the recursion: evaluate(n) calls evaluate(dep) for every dependency of n before computing n's value, so dependencies are always resolved before the names that depend on them — a natural lazy topological order.
Complexity summary
| Stage | set_var | get_var |
|---|---|---|
| 1 | O(1) | O(1) |
| 2 | O(total expression sizes) | O(1) |
| 3 | O(affected subgraph size) | O(1) |
Edge cases
- Redefining a name from an expression back to a literal removes the old dependency edges from
dependents; stale edges would cause phantom recomputes and false cycle detections. - The cycle check must run against the graph before any mutation. Mutating first and then detecting a cycle leaves the store in a partially updated state.
- A name referenced in an expression but never defined evaluates to
None, and any expression that transitively reaches it also evaluates toNonewithout raising.
import re
from typing import List, Optional
def run_config_store(operations: List[str], arguments: List[List]) -> List[Optional[int]]:
if len(operations) != len(arguments):
raise ValueError("operations and arguments must have equal length")
definitions = {} # name -> parsed definition
values = {} # name -> cached resolved int or None
dependents = {} # name -> set of names that directly reference name
results = []
def parse(value):
"""Return a structured definition from a raw int or expression string."""
if isinstance(value, int):
return ("literal", value)
if not isinstance(value, str) or not value.startswith("="):
raise ValueError("value must be an int or a string starting with '='")
body = value[1:]
if not body:
raise ValueError("empty expression")
terms = []
for piece in body.split("+"):
piece = piece.strip()
if not piece:
raise ValueError("invalid expression")
try:
terms.append(("literal", int(piece)))
except ValueError:
if not re.fullmatch(r"[A-Za-z_]\w*", piece):
raise ValueError("invalid term in expression")
terms.append(("name", piece))
return ("expression", terms)
def direct_deps(definition):
"""Return the set of names directly referenced by a definition."""
if definition is None or definition[0] == "literal":
return set()
return {term for kind, term in definition[1] if kind == "name"}
for operation, args in zip(operations, arguments):
if operation == "get_var":
results.append(values.get(args[0]))
continue
if operation != "set_var":
raise ValueError(f"unknown operation: {operation!r}")
name, raw = args
new_def = parse(raw)
new_deps = direct_deps(new_def)
# --- Cycle detection (read-only graph walk) ---
stack = list(new_deps)
visited = set()
has_cycle = False
while stack:
current = stack.pop()
if current == name:
has_cycle = True
break
if current in visited:
continue
visited.add(current)
stack.extend(direct_deps(definitions.get(current)))
if has_cycle:
results.append("ValueError")
continue
# --- Commit: update dependency edges ---
old_deps = direct_deps(definitions.get(name))
for dep in old_deps:
dependents.get(dep, set()).discard(name)
for dep in new_deps:
dependents.setdefault(dep, set()).add(name)
definitions[name] = new_def
dependents.setdefault(name, set())
# --- Find all affected entries (name + transitive dependents) ---
affected = {name}
stack = [name]
while stack:
current = stack.pop()
for dependent in dependents.get(current, ()):
if dependent not in affected:
affected.add(dependent)
stack.append(dependent)
# --- Evaluate affected entries in dependency order ---
computed = {}
visiting = set()
def evaluate(current):
if current not in affected:
return values.get(current)
if current in computed:
return computed[current]
if current in visiting:
return None
visiting.add(current)
defn = definitions.get(current)
if defn is None:
result = None
elif defn[0] == "literal":
result = defn[1]
else:
total = 0
result = 0
for kind, term in defn[1]:
part = term if kind == "literal" else evaluate(term)
if part is None:
result = None
break
total += part
else:
result = total
visiting.discard(current)
computed[current] = result
return result
for affected_name in affected:
evaluate(affected_name)
values.update(computed)
results.append(None)
return results