Bold Words in String - Problem
Bold Words in String
You're working on a text editor that needs to highlight keywords by making them bold. Given an array of
The challenge is to use the minimum number of tags possible. If keywords overlap or are adjacent after bolding, merge their tags into a single
Example: If we need to bold "ab" and "bc" in "abcdef", instead of
Goal: Return the string with properly merged bold tags using the minimum number of tag pairs.
You're working on a text editor that needs to highlight keywords by making them bold. Given an array of
words (keywords to highlight) and a string s, your task is to wrap all occurrences of these keywords with <b> and </b> tags.The challenge is to use the minimum number of tags possible. If keywords overlap or are adjacent after bolding, merge their tags into a single
<b>...</b> pair.Example: If we need to bold "ab" and "bc" in "abcdef", instead of
<b>ab</b><b>bc</b>def, we should return <b>abc</b>def since they overlap.Goal: Return the string with properly merged bold tags using the minimum number of tag pairs.
Input & Output
example_1.py โ Basic Overlapping
$
Input:
words = ["ab", "bc"], s = "aabcd"
โบ
Output:
"a<b>abc</b>d"
๐ก Note:
"ab" matches at position 1-2, "bc" matches at position 2-3. Since they overlap at position 2, we merge them into one bold region covering positions 1-3.
example_2.py โ Multiple Separate Regions
$
Input:
words = ["ab", "cd"], s = "aabcde"
โบ
Output:
"a<b>ab</b><b>cd</b>e"
๐ก Note:
"ab" matches at position 1-2, "cd" matches at position 3-4. They don't overlap, so we create two separate bold regions.
example_3.py โ Adjacent Keywords
$
Input:
words = ["abc", "123"], s = "aabc123"
โบ
Output:
"a<b>abc123</b>"
๐ก Note:
"abc" matches at position 1-3, "123" matches at position 4-6. Since they're adjacent (position 3 ends, position 4 starts), we merge them into one bold region.
Constraints
- 1 โค words.length โค 50
- 1 โค words[i].length โค 10
- 1 โค s.length โค 500
- words[i] and s consist of lowercase English letters only
- All strings in words are unique
Visualization
Tap to expand
Understanding the Visualization
1
Identify Keywords
Find all occurrences of keywords in the text - like marking sticky notes
2
Mark Positions
Mark every character position that should be highlighted
3
Merge Regions
Combine adjacent or overlapping marked regions into continuous highlights
4
Apply Tags
Add <b> and </b> tags around each continuous highlighted region
Key Takeaway
๐ฏ Key Insight: This problem is essentially "Merge Intervals" in disguise! Once you find all keyword matches as intervals, merge overlapping ones and apply bold tags to the merged regions.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code