Problem Description
Given an array of keywords (words) and a string s, insert bold tags ( and ) around all occurrences of each keyword in s. Overlapping or consecutive occurrences should be merged to use the least number of tags possible, forming a valid tag structure.
Key Insights
- Mark each character in s that is part of any keyword.
- Use an auxiliary boolean array to track which indices require bold formatting.
- Merge consecutive bold regions so that overlapping or adjacent keywords are wrapped in a single pair of bold tags.
- Iterate over s once more to insert the tags based on the marked positions.
Space and Time Complexity
Time Complexity: O(n * m * k) worst-case, where n is the length of s, m is the number of words, and k is the average length of each word.
Space Complexity: O(n) due to the auxiliary boolean marker array and the output string.
Solution
The algorithm uses the following steps:
- Create a boolean array of the same length as s, initially set to False. This array will indicate which characters should be bolded.
- For every word in the keywords, find all occurrences in s and mark the corresponding indices in the boolean array to True.
- Traverse s and build the result string. Whenever a bold region is encountered (a sequence of indices marked True), wrap the sequence with and tags. Ensure to merge any contiguous bold regions to avoid extra tags.
- Return the constructed string with minimal bold tags.
This approach uses simple string matching, an auxiliary array for marking, and a linear pass to produce the final result.