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 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
Bold Words in String - Step by StepOriginal String:a a b c d"ab" at pos 1-2"bc" at pos 2-3Overlap!Merged Region: positions 1-3Final Result:"a<b>abc</b>d"๐Ÿ’ก Key Insight: Merge overlapping intervals like "Merge Intervals" problem!
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.
Asked in
Google 35 Amazon 28 Meta 22 Microsoft 18
31.5K Views
Medium Frequency
~25 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen