Bold Words in String - Problem

Given an array of keywords words and a string s, make all appearances of all keywords words[i] in s bold.

Any letters between <b> and </b> tags become bold.

Return s after adding the bold tags. The returned string should use the least number of tags possible, and the tags should form a valid combination.

Input & Output

Example 1 — Basic Overlapping
$ Input: words = ["ab", "bc"], s = "abcabc"
Output: "<b>abc</b><b>abc</b>"
💡 Note: "ab" matches at positions [0,2) and [3,5). "bc" matches at [1,3) and [4,6). Overlapping intervals [0,2) and [1,3) merge to [0,3), and [3,5) and [4,6) merge to [3,6).
Example 2 — No Overlapping
$ Input: words = ["ab", "cd"], s = "abcd"
Output: "<b>ab</b><b>cd</b>"
💡 Note: "ab" matches at [0,2) and "cd" matches at [2,4). No overlap, so each gets separate bold tags.
Example 3 — Complete Coverage
$ Input: words = ["abc"], s = "abc"
Output: "<b>abc</b>"
💡 Note: Single keyword covers entire string, resulting in one bold region.

Constraints

  • 1 ≤ words.length ≤ 1000
  • 1 ≤ words[i].length ≤ 1000
  • words[i] consists of lowercase English letters only
  • 1 ≤ s.length ≤ 1000
  • s consists of lowercase English letters only

Visualization

Tap to expand
Bold Words in String - Interval Merging INPUT words[] array: "ab" "bc" string s = "abcabc": a 0 b 1 c 2 a 3 b 4 c 5 Found Intervals: "ab" at [0,2), "bc" at [1,3) "ab" at [3,5), "bc" at [4,6) Intervals: [0,2), [1,3), [3,5), [4,6) ALGORITHM STEPS 1 Find All Matches Search each word in s 2 Create Intervals Mark [start, end) for each 3 Sort and Merge Merge overlapping intervals 4 Insert Tags Add bold tags at merged ranges Interval Merging: Before: [0,2) [1,3) [3,5) [4,6) After: [0,3) [3,6) (two separate) FINAL RESULT Tagged String: <b>abc</b><b>abc</b> Indices [0-3) and [3-6) Visual Breakdown: abc BOLD [0,3) abc BOLD [3,6) Why Two Tags? Interval [0,3) ends exactly where [3,6) starts - no overlap! Adjacent but not overlapping. Output: "<b>abc</b><b>abc</b>" Key Insight: The Interval Merging approach treats each keyword match as an interval [start, end). When intervals overlap or touch, they are merged to minimize tags. Here, "ab" and "bc" create overlapping ranges that merge into [0,3) and [3,6). Since these are adjacent (not overlapping), two separate tags are used. TutorialsPoint - Bold Words in String | Interval Merging Approach
Asked in
Google 25 Amazon 18 Microsoft 12
28.5K Views
Medium Frequency
~25 min Avg. Time
892 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