Problem Description
Given a string s and an array of strings words, add a pair of bold tags ( and ) to wrap all substrings in s that match any word in words. If the intervals of matching substrings overlap or are consecutive, they should be merged into a single continuous bold section.
Key Insights
- We need to identify every occurrence of each word in s.
- Overlapping or consecutive intervals should be merged to form one continuous bold region.
- Use an auxiliary data structure (e.g., a boolean array) to mark positions that should be bolded.
- Once the positions are marked, build the final string by inserting bold tags at the appropriate boundaries.
Space and Time Complexity
Time Complexity: O(n * m * k) where n is the length of s, m is the number of words, and k is the average length of the words (due to substring matching). Space Complexity: O(n) for the auxiliary boolean array used to mark bold positions.
Solution
The solution involves two main steps:
- Identify and mark the indices in the string s that are part of any matching word. We do this by iterating over each word and marking every occurrence’s start and end in a boolean array.
- Construct the final string by traversing the boolean array. When encountering a segment of consecutive true values, wrap that segment with and tags.
The key idea is to merge intervals by marking every index that should be bold and then using a single pass to insert tags only when transitioning from non-bold to bold and vice versa.