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 token key, look up key in replacements. If present, emit replacements[key] directly into the output without re-evaluating any % characters contained inside replacements[key].
  • Error reporting: If any extracted key is absent from replacements (or if s ends with an unclosed %), abort and return None.

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^5
  • 0 <= len(replacements) <= 10^5
  • Well-formed templates contain an even number of % characters; run in O(len(s) + R) average time where R is the length of the expanded result.

Step-by-step walkthrough

  1. Understand the rules and error contract

    We are given a template string s and a dictionary replacements mapping placeholder names to replacement strings. As we read s from 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 returns Optional[str]. Returning None immediately gives an unambiguous all-or-nothing contract (raising KeyError is 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 in replacements like any other key.
    • Unclosed %: Even though the statement promises paired % characters, returning None if the string ends mid-placeholder prevents silent bugs on malformed input.
  2. Why calling `str.replace` in a loop fails

    A tempting one-liner is to loop over the dictionary and replace "%" + key + "%" with value. 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 whenever replacements has thousands of unused keys.

  3. Core idea: a two-state left-to-right scanner

    Instead of looping over the dictionary, we scan s once 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 value
    

    Every character ch in s triggers one of four simple actions:

    1. ch != "%" while outside: ch is plain text, so append ch to output_parts.
    2. ch == "%" while outside: a placeholder is starting, so flip inside_placeholder = True.
    3. ch != "%" while inside: ch belongs to the placeholder name, so append ch to key_chars.
    4. ch == "%" while inside: the placeholder just ended! Join key_chars into key. If key is missing from replacements, return None right away; otherwise append replacements[key] to output_parts, clear key_chars, and flip inside_placeholder = False.

    Because replacements[key] goes straight into output_parts without ever entering the character loop, a % inside a replacement value is never parsed as a delimiter.

  4. Write the character scan loop

    In Python, strings cannot be modified in place, so repeated result += piece can copy the growing string over and over in O(R^2) time. Instead, we append pieces to a list output_parts in O(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)
    
  5. Trace Example 1 step by step

    Let's trace s = "u%id%id%role%end" with replacements = {"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 setting inside_placeholder = False), and the 3rd % immediately sets inside_placeholder = True to start collecting "q".

  6. 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 the n characters in s at most once. Across the whole scan, joining key_chars and hashing each key for its hash map (dict — a key-value table with O(1) average lookup time per character hashed) processes fewer than n total key characters. Appending replacement string references to output_parts takes O(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 copies R output characters once in O(R) time.
  • Space: O(n + R). key_chars holds at most n characters and output_parts holds at most n string references (O(n)), while the final joined result string occupies O(R) characters.

Edge cases

  • Empty input "": The loop does not run, inside_placeholder stays False, and "".join([]) returns "".
  • Plain text with no % signs: Every character goes directly to output_parts, and unused keys in replacements are never touched.
  • Back-to-back placeholders "%p%%q%": The 2nd % closes "p" and flips inside_placeholder to False; the 3rd % immediately flips inside_placeholder back to True for "q" (Example 3).
  • Empty placeholder "%%": Since % has no escape sequence, "%%" forms a valid placeholder with key ""; it substitutes replacements[""] if "" is present, or returns None otherwise.
  • Empty replacement value {"k": ""}: Appending "" removes %k% cleanly ("a%k%b" becomes "ab").
  • Replacement value containing %: Because replacements[key] is appended straight to output_parts and never fed back into the loop, "%a%" with {"a": "%b%", "b": "NO"} returns "%b%".
  • Missing key ("item=%code%" or "%a% and %missing%"): Failing fast returns None instead of leaking partial output (Example 4).
  • Unclosed trailing %: Caught by if inside_placeholder: return None after the loop.

Common mistakes

  • Looping s = s.replace(...) over replacements: Re-scans substituted values, pairs % signs out of order on "%a%b%c%", fails to detect unknown keys, and runs in O(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 to O(R^2) time on large inputs. Collecting pieces in a list and calling "".join(output_parts) once guarantees O(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, parts has odd length: even indices (0, 2, 4, ...) are literal text runs and odd indices (1, 3, 5, ...) are placeholder keys. If len(parts) % 2 == 0, a % was unclosed. This also runs in O(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 with s.find("%", pos) and append whole substrings s[pos:next_pct]. Asymptotic complexity is still O(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_placeholder and key_chars across chunk boundaries, since a %key% token may start near the end of chunk 1 and finish at the beginning of chunk 2. Memory drops from O(n + R) to O(chunk_size + max_key_length) — though you should enforce a maximum key length so a malformed stream missing a closing % cannot buffer infinite bytes in key_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_placeholder is False, key_chars must be empty (len(key_chars) == 0); at loop termination on valid paired input, inside_placeholder must be False; the input dictionary replacements must never be mutated; and on success, the output length must equal len(s) minus (len(key) + 2) for every substituted placeholder plus len(replacements[key]). In production, raising a custom MissingPlaceholderError(key, offset) with the 0-based index of the opening % is also much easier to debug than bare None.
  • What unit test cases best target boundary indexing, repeated keys, prefix collisions, and delimiter pairing order? For boundary indexing, test placeholders at index 0 and at len(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 in replacements as a decoy) and "%a%" mapped to "%b%", plus a randomized differential test comparing substitute_placeholders against s.split("%").

Follow-up questions

Similar questions

More Zillow interview questions

All 3 Zillow questions →