Token Replace

Token Replace

A template contains tokens wrapped in braces, like {name}. Given a map of token names to values, return the template with every token replaced by its value. A token with no rule is left untouched (braces and all).

tokenReplace(template, rules)

Input format: template | rules, rules as space-separated name=value entries.

Examples

"hi {name}", rules name=sam        // → "hi sam"
"{a}-{b}", rules a=1 b=2           // → "1-2"
"{x} stays", (no rule for x)       // → "{x} stays"

Walkthrough

Thinking it through

This is text-scanning: walk the template character by character, recognizing a special syntax (braces) and passing everything else through unchanged. "Most characters get copied, but a specific marker triggers special handling" is common to a wide range of parsing tasks.

Building the scan

Walk with a position pointer, building output as you go. At each position:

  • Not an opening brace: copy the character, advance one position.
  • An opening brace: search forward for the closing brace. Everything between is the token's name.

Handling the token once identified

Check if the name exists in the rules. If yes, replace the entire {name} span with the rule's value. If no, the problem specifies leaving it completely untouched — copy the literal {name} through, not dropping it or erroring.

Either way, advance the pointer past the closing brace, resuming the scan right after the token.

An edge case worth noting

An opening brace with no matching closing brace anywhere after it means no complete token to extract — treat that brace as an ordinary literal character and continue scanning normally.

Why a single left-to-right scan suffices

Since tokens don't nest or overlap here (that's reserved for token-transform), you never look backward — each character or token resolves the moment you encounter it, with steady forward progress.

Complexity

Each character is visited a constant number of times — O(n) time, O(n) space for the output.

main.py
Console
Press Run to execute your code, or Submit to test and complete this problem.