Add Bold Tag in String - Problem
Imagine you're building a text editor that needs to highlight search results in a document. You have a string s and an array of words that represent search terms. Your task is to wrap all occurrences of these words in the string with <b> and </b> tags.
Here's the challenge: if two highlighted regions overlap or are consecutive, you must merge them into a single bold tag pair. This prevents messy HTML like <b>hel</b><b>lo</b> and instead produces clean <b>hello</b>.
Goal: Return the string with properly merged bold tags around all matching substrings.
Input & Output
example_1.py โ Basic word matching
$
Input:
s = "abcxyz", words = ["abc", "123"]
โบ
Output:
"<b>abc</b>xyz"
๐ก Note:
Only "abc" appears in the string, so we wrap it with bold tags. "123" doesn't appear, so it's ignored.
example_2.py โ Overlapping words
$
Input:
s = "aaabbcc", words = ["aaa", "aab", "bc"]
โบ
Output:
"<b>aaabbc</b>c"
๐ก Note:
"aaa" matches [0,2], "aab" matches [1,3], "bc" matches [4,5]. Since [0,2] and [1,3] overlap, and [3,4] are adjacent to [4,5], we merge them all into one bold region [0,5].
example_3.py โ Separate bold regions
$
Input:
s = "cccccccc", words = ["cc", "c"]
โบ
Output:
"<b>cccccccc</b>"
๐ก Note:
Both "c" and "cc" match at multiple overlapping positions throughout the string. All matches overlap, so the entire string becomes one bold region.
Visualization
Tap to expand
Understanding the Visualization
1
Find Keywords
Scan through the document and identify all keyword positions
2
Mark Regions
Convert keyword positions into highlight regions (intervals)
3
Merge Overlaps
Combine overlapping or touching highlight regions
4
Apply Highlighting
Add bold tags around the final merged regions
Key Takeaway
๐ฏ Key Insight: Think of this problem as highlighting text in a document - find all matches, then merge overlapping highlights for a clean result.
Time & Space Complexity
Time Complexity
O(n * k)
n is string length, k is maximum word length (much better than naive O(n*m*k))
โ Linear Growth
Space Complexity
O(m + n)
Hash set for words plus interval list
โก Linearithmic Space
Constraints
- 1 โค s.length โค 1000
- 0 โค words.length โค 50
- 1 โค words[i].length โค 50
- s and words[i] consist of English letters only
- All strings in words are unique
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code