Fill In Percent-Delimited Tokens From a Lookup Table
StringsAuto-graded · 22 test casesLast updated
Scan a string left to right, replacing each %key% token with its mapped value and returning None when a key is missing; tests careful linear string parsing.
Fill In Percent-Delimited Tokens From a Lookup Table
You are given a template string template and a dictionary values that maps string keys to string replacement values. Build and return the string obtained by expanding every token in the template.
Tokens
The % character is a delimiter. Each token begins with one % and ends at the next % after it. The characters strictly between those two delimiters form the key (for example, the token %city% has key city).
Rules
- Read
templatefrom left to right. - Characters that are not part of a token are copied to the output unchanged.
- For each token, look up its key in
values:- If the key is present, write the mapped value to the output in place of the whole token, including both
%characters. - If the key is absent, the whole function returns
None.
- If the key is present, write the mapped value to the output in place of the whole token, including both
- Replacement values are inserted exactly as given. They are not scanned again for further tokens.
- Every
%intemplatetakes part in exactly one token, so the%characters always come in matched pairs. There is no escape syntax. - Two tokens may sit directly next to each other, as in
%a%%b%, which holds the tokens%a%and%b%. - A template with no
%characters is returned unchanged.
Task
Implement expand_tokens(template, values) that returns the expanded string, or None if any token's key is missing from values.
The solution should run in time linear in the length of the template plus the size of the output, not counting dictionary lookups.
Constraints
templateis a string, possibly empty.- The number of
%characters intemplateis even. valuesis a dictionary from strings to strings; it may be empty.- A key between two
%characters may be an empty string (%%); it is looked up like any other key. - Return type is
stron success, orNoneon failure.
Examples
Example 1
Input: expand_tokens('a%sd%fasd%dog%sdfisan', {'sd': 'HELLO', 'dog': 'CAT'})
Output: 'aHELLOfasdCATsdfisan'
Example 2
Input: expand_tokens('hello %name%!', {'name': 'world'})
Output: 'hello world!'
Example 3
Input: expand_tokens('%a%%b%', {'a': 'x', 'b': 'y'})
Output: 'xy'
Example 4
Input: expand_tokens('plain text', {'unused': 'value'})
Output: 'plain text'
Hints
Hint 1
Walk through the string with an index. Either you are on ordinary text or you are on a `%` that opens a token.
Hint 2
When you see an opening `%`, find the next `%` after it. Everything in between is the key to look up.
Hint 3
After handling a token, resume scanning just past its closing `%`. Collect pieces in a list and join once at the end to stay linear, and return `None` immediately on a missing key.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Scan the template once with an index i and collect output pieces in a list.
- If
template[i]is not%, advance to the next%(or the end) and append that whole plain-text run. - If
template[i]is%, it opens a token. Usefindto locate the next%after it; the text between them is the key. If the key is not invalues, returnNone. Otherwise appendvalues[key]and continue from the character after the closing%.
At the end, join the pieces into one string.
Why it is correct
Because % characters are guaranteed to be paired and there is no escaping, each % encountered while scanning in plain-text mode must be an opening delimiter, and the next % is its closing partner. Consuming both delimiters together means the scan never misinterprets a closing % as an opener, so adjacent tokens like %a%%b% are parsed as %a% followed by %b%. Replacement values are appended directly and never re-scanned, which matches the rules. Plain text is copied verbatim, and a missing key triggers the required None result.
Complexity
- Time: O(n + output size) for a template of length
n, since each character is visited a constant number of times, plus the cost of dictionary lookups. - Space: O(n + output size) for the list of pieces and the final string.
Reference solution
from typing import Dict, Optional
def expand_tokens(template: str, values: Dict[str, str]) -> Optional[str]:
parts = []
i = 0
n = len(template)
while i < n:
if template[i] != '%':
start = i
while i < n and template[i] != '%':
i += 1
parts.append(template[start:i])
else:
end = template.find('%', i + 1)
key = template[i + 1:end]
if key not in values:
return None
parts.append(values[key])
i = end + 1
return ''.join(parts)