Variable Registry With Deep Reference Expansion and Cycle Detection
Data Structure DesignAuto-graded · 17 test casesLast updated
Tests recursive variable substitution with memoization, cycle detection across direct and indirect references, and clean handling of undefined variable references.
Variable Registry With Deep Reference Expansion and Cycle Detection
You are building a lightweight variable registry that stores named values and resolves references embedded in text.
Implement a simulation of this registry by processing a sequence of operations. Each operation is one of the following:
"set"— Store a variable under the given name with the given value. If the name already exists, overwrite it. ReturnsNone."get"— Return the raw stored value (unexpanded) for the given name, orNoneif the name is not present."remove"— Delete the variable with the given name if it exists. ReturnsNone."substitute"— Resolve all variable references in the given text and return the resulting string (see expansion rules below).
Reference Syntax
Inside any text (including stored values), a reference to a variable named foo is written as ${foo}.
Expansion Rules
When substitute is called on a text:
- Scan the text from left to right for patterns of the form
${name}. - When a reference is found, look up
namein the registry.- If
nameis not in the registry, leave the reference exactly as written (e.g.${missing}stays${missing}). - If
nameexists, replace the reference with that variable's value and recursively expand any references inside that value. There is no depth limit.
- If
- Values are expanded on demand; the registry stores raw values.
Cycle Detection
If expanding a reference would require expanding a variable that is already being expanded in the current call chain, a cycle exists. In that case, substitute must return a dictionary:
{"error": "cycle: v1 -> v2 -> ... -> v1"}
The cycle path lists each variable in the order they were first encountered, then repeats the starting variable at the end. The cycle detection must not trigger when a variable is simply referenced from more than one place (shared dependencies are fine).
If no cycle is present and no other error occurs, substitute returns the fully expanded string.
Function Interface
def variable_registry(operations: List[str], arguments: List[List[str]]) -> List[object]:
operations: a list of operation names as described above.arguments: parallel list of argument lists. Each entry contains the arguments for the corresponding operation."set":[name, value]"get":[name]"remove":[name]"substitute":[text]
- Returns a list with one entry per operation, matching the return values described above.
Constraints
1 <= len(operations) <= 1000- Variable names contain only letters (
a–z,A–Z), digits (0–9), and underscores (_). They do not start with a digit. - Stored values and substitute inputs are non-empty strings of printable ASCII characters.
- Stored values may themselves contain
${name}references. - The registry state persists across operations within the same call (i.e. a
setaffects all later operations). - A reference with no closing
}is treated as a literal and left unchanged. - References do not nest inside the name portion (no
${user_${env}}).
Examples
Example 1
Input: variable_registry(['set', 'set', 'set', 'substitute', 'substitute', 'get'], [['host', 'db.internal'], ['port', '5432'], ['url', '${host}:${port}/app'], ['connect to ${url}'], ['${missing}'], ['host']])
Output: [None, None, None, 'connect to db.internal:5432/app', '${missing}', 'db.internal']
Example 2
Input: variable_registry(['set', 'set', 'substitute'], [['a', 'x${b}'], ['b', '${a}'], ['${a}']])
Output: [None, None, {'error': 'cycle: a -> b -> a'}]
Hints
Hint 1
Store raw values in a plain dictionary. Expand references only when substitute is called, not when set is called — that way updates stay simple and the expansion always reflects the current registry state.
Hint 2
For expand(text, path): scan left to right for ${ ... } patterns. When you find a reference, check if the variable name already appears in path (cycle!) before recursing into its value. Append the name to path for the recursive call.
Hint 3
A variable can be referenced from multiple places without forming a cycle — being referenced twice is not the same as being in the current expansion chain. Use the call-stack path list, not a global visited set, to tell the difference.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Core idea
Store every variable's raw value in a plain dictionary and expand references lazily, only when substitute is called. This keeps set and remove trivially O(1) and ensures that changes to the registry are always reflected in future substitutions.
Scanning for references
Instead of using repeated str.replace passes (which would require multiple scans and can mishandle overlapping references), scan the input text once from left to right. When the two-character sequence ${ is found, read forward to locate the closing }. Everything outside a well-formed ${...} token is copied to the output verbatim.
Depth-first expansion with cycle detection
Keep a path list that records the chain of variable names currently being expanded (the active call stack). When a reference ${name} is found:
- If
nameis absent from the registry, copy the token as-is. - If
nameis already inpath, a cycle exists. Slice out the portion of the path from the first occurrence ofnameto the end, appendnameagain, and return an error dict:{"error": "cycle: v1 -> v2 -> ... -> v1"}. - Otherwise, recurse into
expand(registry[name], path + [name]).
Using the path list (the current call chain) rather than a global visited set is what distinguishes a genuine cycle from a variable that is simply referenced from two different places. A shared dependency is reached via separate, non-overlapping branches of the recursion and never appears in the same path simultaneously.
Any cycle error returned by a recursive call is propagated immediately up the chain, so the outermost substitute call returns the error dict as its result.
Why this is correct
- Single-pass scan avoids double-counting or missing references.
- The path tracks only the current expansion chain, not all variables ever visited, so a diamond-shaped dependency graph (variable referenced twice) does not falsely trigger a cycle.
- Undefined references are preserved exactly, matching the specified policy.
- A
${with no closing}is treated as a literal character, preventing an infinite scan.
Complexity
Let V be the number of distinct variables and L be the total length of all stored values.
- Time per
substitutecall: O(T + E) where T is the length of the input text and E is the total length of all text expanded during the call. In the worst case the output can be exponentially larger than the input (a variable whose value references the same large variable many times), but each stored value is read at most once per expansion path of length V, so the recursion depth is bounded by V. - Space: O(V) for the registry and O(V) for the maximum recursion depth (path length). The output string itself can be large.
Reference solution
from typing import List
def variable_registry(operations: List[str], arguments: List[List[str]]) -> List[object]:
registry = {}
results = []
def substitute(text):
"""Top-level entry point for a single substitute call."""
def expand(s, path):
"""
Recursively expand all ${name} references in s.
path is the list of variable names currently being expanded
(the active call chain), used to detect cycles.
Returns either the fully expanded string or a cycle-error dict.
"""
out = []
i = 0
while i < len(s):
# Look for the opening marker ${
if s[i:i+2] == '${':
# Find the matching closing brace
j = i + 2
while j < len(s) and s[j] != '}':
j += 1
if j < len(s):
# Well-formed reference: ${s[i+2:j]}
var_name = s[i+2:j]
if var_name not in registry:
# Undefined — preserve the original token
out.append(s[i:j+1])
elif var_name in path:
# Cycle detected: build the descriptive path string
cycle_start = path.index(var_name)
cycle_vars = path[cycle_start:] + [var_name]
return {"error": "cycle: " + " -> ".join(cycle_vars)}
else:
# Expand the variable's raw value, extending the path
expanded = expand(registry[var_name], path + [var_name])
if isinstance(expanded, dict) and "error" in expanded:
# Propagate any cycle error up the call chain
return expanded
out.append(expanded)
i = j + 1
else:
# No closing brace — treat the stray ${ as a literal character
out.append(s[i])
i += 1
else:
out.append(s[i])
i += 1
return ''.join(out)
return expand(text, [])
for op, args in zip(operations, arguments):
if op == "set":
registry[args[0]] = args[1]
results.append(None)
elif op == "get":
results.append(registry.get(args[0]))
elif op == "remove":
registry.pop(args[0], None)
results.append(None)
elif op == "substitute":
results.append(substitute(args[0]))
return results