Percent-Delimited Template Placeholder Expander
Medium · Coding & Algorithms · Machine Learning Engineer · Technical Screen
Problem Statement
Implement substitute_placeholders(s: str, replacements: Dict[str, str]) -> Optional[str] to expand %-delimited template tokens in a single left-to-right pass.
You receive a template string s and a lookup dictionary replacements mapping token names to substitute strings. Process s from index 0 to len(s) - 1 under the following rules:
- Literal runs: Characters appearing outside
%...%delimiters are copied verbatim into the output. - Strict left-to-right
%pairing: The 1st%opens a token name, the 2nd%closes that token name, the 3rd%opens the next token name, and so on. No escape sequence exists for%(in particular,"%%"represents a token whose name is the empty string""). - Single-pass expansion: Whenever a closing
%completes a tokenkey, look upkeyinreplacements. If present, emitreplacements[key]directly into the output without re-evaluating any%characters contained insidereplacements[key]. - Error reporting: If any extracted
keyis absent fromreplacements(or ifsends with an unclosed%), abort and returnNone.
Examples
Example 1
Input: s = "u%id%id%role%end", replacements = {"id": "42", "role": "ADMIN"}
Output: "u42idADMINend"
Walk-through: "u" is literal text; %id% expands to "42"; the next "id" lies outside %...% so it stays "id"; %role% expands to "ADMIN"; and "end" is copied literally, giving "u42idADMINend".
Example 2
Input: s = "%host%:%port%", replacements = {"host": "localhost", "port": "8080"}
Output: "localhost:8080"
Walk-through: %host% expands to "localhost", the colon ":" is copied unchanged, and %port% expands to "8080".
Example 3
Input: s = "%p%%q%", replacements = {"p": "left-", "q": "right"}
Output: "left-right"
Walk-through: The 2nd % closes token "p" (emitting "left-") and the adjacent 3rd % immediately opens token "q" (emitting "right").
Example 4
Input: s = "item=%code%", replacements = {"other": "99"}
Output: None
Walk-through: Token "code" is missing from replacements, so expansion fails fast and returns None rather than partial text.
Constraints
0 <= len(s) <= 10^50 <= len(replacements) <= 10^5- Well-formed templates contain an even number of
%characters; run inO(len(s) + R)average time whereRis the length of the expanded result.
Step-by-step walkthrough
Understand the rules and error contract
We are given a template string
sand a dictionaryreplacementsmapping placeholder names to replacement strings. As we readsfrom left to right,%signs pair up strictly in order: the 1st%opens a placeholder, the 2nd%closes it, the 3rd%opens the next one, and so on.s = "u % i d % i d % r o l e % e n d" ^ |-----| ^^^ |---------| ^^^^^ text key text key text "id" "role" | | "42" "ADMIN" Result: "u42idADMINend"Notice that
"id"also appears immediately after%id%as literal text, which stays untouched because it sits outside%...%pairs.Before coding, we also settle three contract details:
- Missing keys return
None: The problem asks us to define how missing keys are reported, and the function signature returnsOptional[str]. ReturningNoneimmediately gives an unambiguous all-or-nothing contract (raisingKeyErroris the other valid option in Python, and our test suite accepts either). - Empty key
%%: Because there is no%escaping rule, two adjacent%%delimiters enclose the empty key"", which is looked up inreplacementslike any other key. - Unclosed
%: Even though the statement promises paired%characters, returningNoneif the string ends mid-placeholder prevents silent bugs on malformed input.
- Missing keys return
Why calling `str.replace` in a loop fails
A tempting one-liner is to loop over the dictionary and replace
"%" + key + "%"withvalue. That shortcut breaks correctness in three separate ways:Bug 1 (re-scanning replacement values): s = "%a%", replacements = {"a": "%b%", "b": "NO"} 1st replace ("a"): "%a%" -> "%b%" 2nd replace ("b"): "%b%" -> "NO" (WRONG! Expected "%b%") Bug 2 (breaking left-to-right '%' pairing): s = "%a%b%c%", replacements = {"b": "X", "a": "1", "c": "3"} Left-to-right pairing says placeholders are %a% and %c%, while "b" is plain text -> "1b3". If "b" is replaced first, "%b%" matches the 2nd and 3rd '%', producing "%aXc%"! Bug 3 (silent missing keys): s = "hi %unknown%", replacements = {} Loop finishes and returns "hi %unknown%" instead of reporting an error.Plus, scanning the whole string once per dictionary entry takes
O(len(s) * len(replacements))time, which wastes work wheneverreplacementshas thousands of unused keys.Core idea: a two-state left-to-right scanner
Instead of looping over the dictionary, we scan
sonce from left to right using a two-state scanner (a tiny state machine that remembers only one boolean: whether we are currently outside or inside a%...%placeholder).see '%' +-----------+ ----------> +------------+ | OUTSIDE | | INSIDE | | (copy ch) | <---------- | (build key)| +-----------+ see '%': +------------+ lookup key & emit valueEvery character
chinstriggers one of four simple actions:ch != "%"while outside:chis plain text, so appendchtooutput_parts.ch == "%"while outside: a placeholder is starting, so flipinside_placeholder = True.ch != "%"while inside:chbelongs to the placeholder name, so appendchtokey_chars.ch == "%"while inside: the placeholder just ended! Joinkey_charsintokey. Ifkeyis missing fromreplacements, returnNoneright away; otherwise appendreplacements[key]tooutput_parts, clearkey_chars, and flipinside_placeholder = False.
Because
replacements[key]goes straight intooutput_partswithout ever entering the character loop, a%inside a replacement value is never parsed as a delimiter.Write the character scan loop
In Python, strings cannot be modified in place, so repeated
result += piececan copy the growing string over and over inO(R^2)time. Instead, we append pieces to a listoutput_partsinO(1)time per piece and call"".join(output_parts)once at the very end.from typing import Any, Dict, List, Optional, Set, Tuple def substitute_placeholders(s: str, replacements: Dict[str, str]) -> Optional[str]: # output_parts: literal characters and substituted strings, e.g. ["u", "42", "i", "d"] output_parts: List[str] = [] # key_chars: characters collected inside the current %...%, e.g. ["i", "d"] key_chars: List[str] = [] # inside_placeholder: True after an opening '%', False once its closing '%' is read inside_placeholder = False # Phase 1: Scan left-to-right once so '%' delimiters pair strictly in order. for ch in s: if ch == "%": if inside_placeholder: # Closing '%': finish the key and look it up immediately. key = "".join(key_chars) if key not in replacements: # Fail fast so callers never receive a half-substituted string. return None # Append the replacement directly to output_parts so any '%' inside # the replacement value is treated as plain output, never re-parsed. output_parts.append(replacements[key]) key_chars = [] inside_placeholder = False else: # Opening '%': switch from copying literal text to collecting a key. inside_placeholder = True elif inside_placeholder: key_chars.append(ch) else: output_parts.append(ch) # Phase 2: Guard against a trailing unclosed '%' before joining all output pieces. if inside_placeholder: return None return "".join(output_parts)Trace Example 1 step by step
Let's trace
s = "u%id%id%role%end"withreplacements = {"id": "42", "role": "ADMIN"}:Read | inside_placeholder | key_chars | output_parts ----------+--------------------+----------------------+------------------------------------- "u" | False | [] | ["u"] "%" | False -> True | [] | ["u"] "i", "d" | True | ["i", "d"] | ["u"] "%" | True -> False | [] (key="id") | ["u", "42"] "i", "d" | False | [] | ["u", "42", "i", "d"] "%" | False -> True | [] | ["u", "42", "i", "d"] "r".."e" | True | ["r", "o", "l", "e"] | ["u", "42", "i", "d"] "%" | True -> False | [] (key="role") | ["u", "42", "i", "d", "ADMIN"] "e".."d" | False | [] | ["u", "42", "i", "d", "ADMIN", "e", "n", "d"] End of loop: inside_placeholder is False -> "".join(output_parts) == "u42idADMINend"Example 3 (
"%p%%q%"with{"p": "left-", "q": "right"}) works smoothly too: the 2nd%closes"p"(emitting"left-"and settinginside_placeholder = False), and the 3rd%immediately setsinside_placeholder = Trueto start collecting"q".Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple def substitute_placeholders(s: str, replacements: Dict[str, str]) -> Optional[str]: """Replace every %key% placeholder in s with replacements[key]. Returns None if any placeholder key is missing from replacements or if an opening '%' is never closed. """ # output_parts: literal characters and substituted strings, e.g. ["u", "42", "i", "d"] output_parts: List[str] = [] # key_chars: characters collected inside the current %...%, e.g. ["i", "d"] key_chars: List[str] = [] # inside_placeholder: True after an opening '%', False once its closing '%' is read inside_placeholder = False # Phase 1: Scan left-to-right once so '%' delimiters pair strictly in order. for ch in s: if ch == "%": if inside_placeholder: # Closing '%': finish the key and look it up immediately. key = "".join(key_chars) if key not in replacements: # Fail fast so callers never receive a half-substituted string. return None # Append the replacement directly to output_parts so any '%' inside # the replacement value is treated as plain output, never re-parsed. output_parts.append(replacements[key]) key_chars = [] inside_placeholder = False else: # Opening '%': switch from copying literal text to collecting a key. inside_placeholder = True elif inside_placeholder: key_chars.append(ch) else: output_parts.append(ch) # Phase 2: Guard against a trailing unclosed '%' before joining all output pieces. if inside_placeholder: return None return "".join(output_parts)✅ Submit now — all tests should pass.
Intuition & how it works
Imagine reading a form letter out loud while holding a toggle switch: normally you read every character straight onto the page, but the moment you hit a % sign you flip the switch to "label mode," read the label name, look up that label on your cheat sheet when you hit the next %, write down its replacement, and flip the switch back to normal. That mental model is a two-state finite-state machine (an algorithm that processes input one symbol at a time while keeping track of which mode — here outside or inside a placeholder — it is currently in).
Why not just loop over the dictionary and call s.replace("%" + key + "%", value)? First, str.replace modifies the string in place across iterations, so if "%a%" expands to "%b%", a later pass for key "b" will illegally overwrite text that came from a replacement value rather than the original input. Second, str.replace ignores left-to-right % pairing: in "%a%b%c%", "b" is plain text between two placeholders (%a% and %c%), yet replacing "%b%" first hijacks the 2nd and 3rd % signs and corrupts the string into "%aXc%". Third, str.replace leaves unknown %missing% placeholders silently in the output instead of reporting an error, and wastes O(len(s)) work per unused dictionary key.
Let's trace "%a%b%c%" with replacements = {"a": "1", "b": "X", "c": "3"}:
ch='%' -> flip inside=True
ch='a' -> key_chars=['a']
ch='%' -> close key "a" -> append replacements["a"] ("1"), reset key_chars=[], inside=False
ch='b' -> inside is False -> copy literal 'b' to output_parts
ch='%' -> flip inside=True
ch='c' -> key_chars=['c']
ch='%' -> close key "c" -> append replacements["c"] ("3"), reset key_chars=[], inside=False
Joined output: "1b3" ("b" was never treated as a key!)
Complexity
Let n = len(s) be the length of the input string and R be the length of the final output string. We keep both variables in the bound because R can be smaller than n (when keys map to "") or much larger than n (when short keys map to long strings).
- Time:
O(n + R)on average. We inspect each of thencharacters insat most once. Across the whole scan, joiningkey_charsand hashing eachkeyfor its hash map (dict— a key-value table withO(1)average lookup time per character hashed) processes fewer thanntotal key characters. Appending replacement string references tooutput_partstakesO(1)amortized time (average constant cost per append even when the underlying list occasionally resizes) per placeholder, and the single"".join(output_parts)at the end copiesRoutput characters once inO(R)time. - Space:
O(n + R).key_charsholds at mostncharacters andoutput_partsholds at mostnstring references (O(n)), while the final joined result string occupiesO(R)characters.
Edge cases
- Empty input
"": The loop does not run,inside_placeholderstaysFalse, and"".join([])returns"". - Plain text with no
%signs: Every character goes directly tooutput_parts, and unused keys inreplacementsare never touched. - Back-to-back placeholders
"%p%%q%": The 2nd%closes"p"and flipsinside_placeholdertoFalse; the 3rd%immediately flipsinside_placeholderback toTruefor"q"(Example 3). - Empty placeholder
"%%": Since%has no escape sequence,"%%"forms a valid placeholder with key""; it substitutesreplacements[""]if""is present, or returnsNoneotherwise. - Empty replacement value
{"k": ""}: Appending""removes%k%cleanly ("a%k%b"becomes"ab"). - Replacement value containing
%: Becausereplacements[key]is appended straight tooutput_partsand never fed back into the loop,"%a%"with{"a": "%b%", "b": "NO"}returns"%b%". - Missing key (
"item=%code%"or"%a% and %missing%"): Failing fast returnsNoneinstead of leaking partial output (Example 4). - Unclosed trailing
%: Caught byif inside_placeholder: return Noneafter the loop.
Common mistakes
- Looping
s = s.replace(...)overreplacements: Re-scans substituted values, pairs%signs out of order on"%a%b%c%", fails to detect unknown keys, and runs inO(len(s) * len(replacements))time. - Building output with
result += piece: Because Python strings have immutability (a string's characters cannot be changed after creation, so+=allocates a brand-new string), repeated concatenation can degrade toO(R^2)time on large inputs. Collecting pieces in a list and calling"".join(output_parts)once guaranteesO(R). - Forgetting to reset
key_chars = []when closing a placeholder: Without clearing the key buffer, the second placeholder concatenates onto the first ("id"becomes"idrole"). - Treating
"%%"as an escaped literal"%": Many string formatters (printf, Python%formatting) treat"%%"as an escape, whereas here every%opens or closes a placeholder without escaping.
Alternative approaches
- Splitting on
"%"(parts = s.split("%")): When%characters are paired,partshas odd length: even indices (0, 2, 4, ...) are literal text runs and odd indices (1, 3, 5, ...) are placeholder keys. Iflen(parts) % 2 == 0, a%was unclosed. This also runs inO(n + R)time and serves as a concise cross-check in our test suite. - Slice jumping with
s.find("%", pos): Instead of appending literal text one character at a time, jump from one%index to the next withs.find("%", pos)and append whole substringss[pos:next_pct]. Asymptotic complexity is stillO(n + R), with lower Python loop overhead at the cost of extra index arithmetic.
Follow-up questions
- How would you adapt the scanner to process an arbitrarily large character stream without loading the entire template into RAM? A streaming parser (one that reads fixed-size chunks from a file or network socket and writes output incrementally without holding the whole input in RAM) only needs to carry
inside_placeholderandkey_charsacross chunk boundaries, since a%key%token may start near the end of chunk 1 and finish at the beginning of chunk 2. Memory drops fromO(n + R)toO(chunk_size + max_key_length)— though you should enforce a maximum key length so a malformed stream missing a closing%cannot buffer infinite bytes inkey_chars. Because earlier chunks are flushed before a missing key might appear near the end of the stream, either stream output to a temporary file and atomically rename it on clean completion, or switch to an exception/error-trailer protocol. - Which state invariants and error diagnostics would you enforce in a production implementation? An invariant is a condition that must remain true at well-defined checkpoints during execution. Here, whenever
inside_placeholderisFalse,key_charsmust be empty (len(key_chars) == 0); at loop termination on valid paired input,inside_placeholdermust beFalse; the input dictionaryreplacementsmust never be mutated; and on success, the output length must equallen(s)minus(len(key) + 2)for every substituted placeholder pluslen(replacements[key]). In production, raising a customMissingPlaceholderError(key, offset)with the 0-based index of the opening%is also much easier to debug than bareNone. - What unit test cases best target boundary indexing, repeated keys, prefix collisions, and delimiter pairing order? For boundary indexing, test placeholders at index
0and atlen(s) - 1, adjacent placeholders"%p%%q%", single-character text between placeholders, and the empty key"%%". For repeated keys and prefix collisions, test the same key repeated many times ("%x%-%x%-%x%") and keys where one is a prefix of another ("%first%"alongside"%first name%"). For%-pairing order and non-rescanning, test"%a%b%c%"(where"b"is inreplacementsas a decoy) and"%a%"mapped to"%b%", plus a randomized differential test comparingsubstitute_placeholdersagainsts.split("%").
Follow-up questions
- How would you adapt the scanner to process an arbitrarily large character stream without loading the entire template into RAM?
- Which state invariants and error diagnostics would you enforce in a production implementation?
- What unit test cases best target boundary indexing, repeated keys, prefix collisions, and delimiter pairing order?
Similar questions
- Streaming K-th Largest Element Tracker
- Root Causes and Mitigations of LLM Hallucinations
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses
- Place One Hub to Minimize Maximum Grid Distance