Katkat

Replace Delimited Tokens in a String

AmazonSoftware Engineer · Onsite

Last updated

This problem tests string manipulation, hash map lookups, and edge-case handling when parsing nested or malformed delimiters within a template string.

Problem Statement

You are given a template string where tokens are enclosed in curly braces (e.g., {key}). You are also provided with a dictionary mapping keys to replacement values. Write a function that replaces all occurrences of {key} in the string with its corresponding value from the dictionary.

Rules:

  1. If a key is found in the dictionary, replace {key} with the value.
  2. If a key is not found, leave the {key} placeholder as-is in the final string.
  3. If a placeholder is malformed (e.g., {key without a closing brace, or {} empty braces), leave the string segment unchanged.
  4. You do not need to handle nested placeholders (e.g., {a{b}}).

Function Signature

def replace_tokens(template: str, replacements: dict[str, str]) -> str:

Examples

Example 1:

  • Input: template = "Hello {name}, welcome to {place}!", replacements = {"name": "Alice", "place": "Amazon"}
  • Output: "Hello Alice, welcome to Amazon!"

Example 2:

  • Input: template = "Invalid {token and {empty} are ignored", replacements = {"empty": "space"}
  • Output: "Invalid {token and space are ignored"

Constraints

  • template length is between 0 and 10,000 characters.
  • The dictionary can contain up to 1,000 key-value pairs.
  • Time complexity should be linear with respect to the length of the string.

Edge Cases

  • Empty template string.
  • Dictionary missing keys.
  • Consecutive braces or incomplete braces.

Hints

Hint 1

Consider iterating through the string once and identifying the start '{' and end '}' indices of potential tokens.

Hint 2

Using a stack or a simple tracking variable to find the index of the closing brace can help isolate the token key efficiently.

Hint 3

If you find an opening brace but no matching closing brace before the next opening brace or the end of the string, treat the text as literal characters.

Follow-up questions

  • How would you modify your solution to support nested placeholders, such as `{a{b}}`?
  • What changes would be required if the delimiter could be a multi-character string like `{{` and `}}`?
  • How would you optimize this if the template string was extremely large (e.g., several gigabytes) and needed to be processed in a streaming fashion?