Resolve Nested %NAME% Placeholders with Cycle Detection
StringsAuto-graded · 27 test casesLast updated
Expand %NAME% placeholders whose values may reference other placeholders, handling %% escapes, missing names, and circular references.
Render a Template with Nested Placeholders
You are given a text template and a dictionary definitions that maps names to replacement text. Produce the fully rendered text by substituting every placeholder in template.
Token rules
Scan a string from left to right. At each % character, apply the first rule that fits:
- Escape: if the next character is also
%, the pair%%produces one literal%. Both characters are consumed. - Placeholder: otherwise, if the
%is followed by one or more characters from[A-Za-z0-9_]and then another%, the whole%NAME%span is a placeholder for the nameNAME. All of the name characters and the closing%are consumed. - Stray percent: in any other case, the
%is ordinary literal text, and scanning continues with the very next character.
Examples of how text is split:
| Text | Meaning |
|---|---|
100%% done | literal text 100% done |
50% off | literal text 50% off |
%%USER% | literal %, then literal USER% |
%A%B% | placeholder A, then literal B% |
%A %B% | literal %A , then placeholder B |
Substitution
- A placeholder
%NAME%is replaced by the fully rendered form ofdefinitions["NAME"]. - Each definition is itself a string that follows the same token rules, so it may contain
%%escapes and further placeholders, which are rendered recursively. - Every string (the template and each definition) is tokenized exactly once from its own raw text. Text produced by a substitution is final and must never be scanned again. For example, a rendered
%that came from%%can never combine with neighboring characters into a new placeholder.
Errors
- If a placeholder refers to a name that is not a key of
definitions, raiseKeyError. - If rendering a name requires, directly or indirectly, rendering that same name again (including a name whose definition refers to itself), raise
ValueError. - Only definitions that are actually reached while rendering are examined. An unused definition that is broken (missing reference or cycle) must not cause an error.
- If several problems exist, the one met first when processing left to right, depth first, is the one raised.
Return the rendered string.
Constraints
0 <= len(template) <= 10^40 <= len(definitions) <= 1000- Every key of
definitionsmatches[A-Za-z0-9_]+ - All strings contain printable ASCII characters only
- Reference chains may be as long as the number of definitions, so very deep nesting must work
Examples
Example 1
Input: render_template('I am %USER%. My home is %HOME%.', {'USER': 'admin', 'HOME': '/%USER%/home'})
Output: 'I am admin. My home is /admin/home.'
Example 2
Input: render_template('Usage: 100%% completed by %USER%', {'USER': 'alice'})
Output: 'Usage: 100% completed by alice'
Hints
Hint 1
Separate the work into two steps: splitting a raw string into literal pieces and placeholder names, then resolving names. All the % rules belong only in the first step.
Hint 2
Treat each name as a node in a graph and resolve it with a depth-first search. Cache finished names so each is rendered once, and keep a set of names currently being resolved to spot a cycle.
Hint 3
A chain of 1000 names can exceed Python's default recursion limit, so use an explicit stack of frames (name, tokens, next index, output pieces). Never re-tokenize text that has already been rendered.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Split the problem into two independent parts.
1. Tokenizing. A string is turned into a list of pieces: literal text or a placeholder name. A regular expression %%|%([A-Za-z0-9_]+)% does this in one left-to-right pass. At each position it first tries %% (an escape), then %NAME% (a placeholder). If neither matches, the % is not consumed by any token and stays in the literal text between matches. This reproduces the three rules exactly, including cases like %%USER% (escape first, then USER% literal) and %A%B% (placeholder A, then literal B%).
2. Resolving names. Each name is a node in a directed graph, with an edge from X to Y when the definition of X contains %Y%. Rendering a name is a depth-first search:
- A
donecache stores each fully rendered name, so shared dependencies are rendered once and reused. - An
in_progressset holds the names on the current DFS path. Reaching a name that is in progress means a back edge, which is a cycle, soValueErroris raised. This includes a self-reference. - A referenced name missing from
definitionsraisesKeyError.
Because chains can be as long as 1000 names, the DFS uses an explicit stack of frames [name, pieces, next_index, output_pieces] rather than Python recursion. When a frame finishes, its joined text is cached and appended to the parent frame's output.
Why it is correct
- A name's rendered text depends only on its own tokens and the rendered text of the names it references, so caching it is safe and every occurrence yields identical text.
- Each raw string is tokenized once and rendered text is spliced in as final, so an unescaped
%can never merge with its neighbors into a fake placeholder, and literal text that looks like%X%after substitution is never expanded. - Only referenced names are visited, so broken unused definitions never raise. Errors are raised in left-to-right, depth-first order, so the first problem encountered wins.
Complexity
Let T be the template length, V the total length of all definitions, and L the output length.
- Time: O(T + V + L). Each string is tokenized once, each name is rendered once, and each reference is followed once. L can be exponentially large in the worst case, and any algorithm must write that output.
- Space: O(V + number of names + L) for tokens, cache, and the explicit stack.
Reference solution
import re
from typing import Dict
_TOKEN = re.compile(r"%%|%([A-Za-z0-9_]+)%")
def _split(text):
pieces = []
pos = 0
for m in _TOKEN.finditer(text):
pieces.append(text[pos:m.start()])
if m.group(0) == "%%":
pieces.append("%")
else:
pieces.append(("name", m.group(1)))
pos = m.end()
pieces.append(text[pos:])
return pieces
def render_template(template: str, definitions: Dict[str, str]) -> str:
done = {}
in_progress = set()
def resolve(root):
if root in done:
return done[root]
if root not in definitions:
raise KeyError(root)
stack = [[root, _split(definitions[root]), 0, []]]
in_progress.add(root)
while stack:
frame = stack[-1]
name, pieces, idx, out = frame
if idx == len(pieces):
done[name] = "".join(out)
in_progress.discard(name)
stack.pop()
if stack:
stack[-1][3].append(done[name])
continue
piece = pieces[idx]
frame[2] += 1
if isinstance(piece, tuple):
child = piece[1]
if child not in definitions:
raise KeyError(child)
if child in done:
out.append(done[child])
elif child in in_progress:
raise ValueError("Circular dependency detected")
else:
in_progress.add(child)
stack.append([child, _split(definitions[child]), 0, []])
else:
out.append(piece)
return done[root]
result = []
for piece in _split(template):
if isinstance(piece, tuple):
result.append(resolve(piece[1]))
else:
result.append(piece)
return "".join(result)