Problem Description
Given a mapping from single uppercase letter keys to string values (which may themselves contain placeholders in the form %X%), and a text string composed solely of these placeholders separated by underscores, substitute each placeholder with its fully expanded string value. The expanded value is obtained by recursively replacing any nested placeholders, ensuring that the final answer contains no placeholders.
Key Insights
- Use a dictionary (or hash map) to store the mapping from key to value.
- The replacement values may contain nested placeholders, requiring a recursive (or DFS) approach to fully expand each key.
- No cyclic dependencies exist, guaranteeing termination.
- Use memoization to avoid redundant computations while expanding each placeholder.
Space and Time Complexity
Time Complexity: O(N) where N is the total number of characters in the text and all replacement strings combined, since each character is processed a constant number of times. Space Complexity: O(N) due to the storage required for recursion, memoization, and the final expanded strings.
Solution
The main idea is to first convert the list of replacement pairs into a dictionary mapping keys to their replacement strings. Then, use a depth-first search (DFS) with memoization to recursively expand each key’s value by searching for placeholders using a regular expression pattern.
- For each key, if its expanded value is already computed (stored in a memo dictionary), return it immediately.
- Otherwise, scan its value for any placeholders of the form %X% and recursively replace them with their expanded versions.
- After processing all replacements, substitute the placeholders in the main text similarly by applying the DFS expansion. This approach guarantees that each placeholder is expanded fully and only once.