Replace Delimited Tokens in a String
Company: Amazon
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Onsite
Quick Answer: This question evaluates string parsing, token recognition, and dictionary lookup competencies for robust text replacement, including handling malformed placeholders and missing keys.
Constraints
- 0 <= len(s) <= 200000
- Keys in valid placeholders contain only lowercase English letters, digits, and underscores
- replacements maps string keys to string values
Examples
Input: ("Hello ;name:, welcome to ;city:.", {"name": "Alice", "city": "Seattle"})
Expected Output: "Hello Alice, welcome to Seattle."
Explanation: Both ;name: and ;city: are valid placeholders, and both keys exist in replacements.
Input: ("User ;user:, role ;role:.", {"user": "Bob"})
Expected Output: "User Bob, role ;role:."
Explanation: ;user: is replaced with Bob, but ;role: is left unchanged because role is not in the dictionary.
Input: ("Bad ;token and empty ;: plus good ;ok:.", {"token": "X", "ok": "yes"})
Expected Output: "Bad ;token and empty ;: plus good yes."
Explanation: ;token is malformed because it has no closing colon, ;: is malformed because the key is empty, and ;ok: is valid and replaced.
Input: (";a1:;b_2:!", {"a1": "X", "b_2": "Y"})
Expected Output: "XY!"
Explanation: Adjacent placeholders are both valid and should both be replaced.
Input: ("Mix ;bad-key: and ;good_key1:.", {"good_key1": "OK", "bad": "NO"})
Expected Output: "Mix ;bad-key: and OK."
Explanation: ;bad-key: is malformed because '-' is not allowed in a key, so it stays unchanged. ;good_key1: is valid and replaced.
Input: ("", {"name": "Alice"})
Expected Output: ""
Explanation: An empty input string remains empty.
Hints
- Scan the string from left to right. When you see ';', try extending a second pointer over a valid key and check whether the next character is ':'.
- Build the answer using a list of string pieces and join at the end to avoid expensive repeated string concatenation.