Add Bold Tag in String - Problem

You are given a string s and an array of strings words. You should add a closed pair of bold tag <b> and </b> to wrap the substrings in s that exist in words.

Rules for bold tagging:

  • If two such substrings overlap, you should wrap them together with only one pair of bold tags
  • If two substrings wrapped by bold tags are consecutive, you should combine them

Return s after adding the bold tags.

Input & Output

Example 1 — Basic Case
$ Input: s = "abcxyz123", words = ["abc", "123"]
Output: "<b>abc</b>xyz<b>123</b>"
💡 Note: "abc" appears at start (positions 0-2) and "123" appears at end (positions 6-8). Both are wrapped with bold tags separately since they don't overlap.
Example 2 — Overlapping Words
$ Input: s = "aaabbcc", words = ["aaa", "aab", "bc"]
Output: "<b>aaabbc</b>c"
💡 Note: "aaa" matches at 0-2, "aab" matches at 1-3, "bc" matches at 4-5. Since positions 0-5 are all marked bold and consecutive, they merge into one bold tag.
Example 3 — No Matches
$ Input: s = "hello", words = ["world", "test"]
Output: "hello"
💡 Note: None of the words appear in the string, so no bold tags are added.

Constraints

  • 1 ≤ s.length ≤ 1000
  • 0 ≤ words.length ≤ 100
  • 1 ≤ words[i].length ≤ 100
  • s and words[i] consist of English letters only

Visualization

Tap to expand
Add Bold Tag in String INPUT String s: a b c x y z 1 2 3 0 1 2 3 4 5 6 7 8 Words Array: "abc" "123" HashSet for O(1) lookup Bold[] Array (init false): F F F F F F F F F ALGORITHM STEPS 1 Build HashSet Add all words for O(1) lookup 2 Mark Bold Positions For each i, check all substrings T T T F F F T T T 3 Find Consecutive Ranges Merge overlapping bold regions [0-2] [6-8] 4 Build Result String Insert tags at boundaries if (bold[i] && !bold[i-1]) append("<b>") if (bold[i] && !bold[i+1]) append("</b>") FINAL RESULT Output String: <b> abc </b> xyz <b> 123 </b> "<b>abc</b>xyz<b>123</b>" OK - Valid Output Complexity Analysis Time: O(n * m * k) n=len(s), m=words, k=max word Space: O(n) bold array Key Insight: Using a HashSet enables O(1) word lookup. The boolean array marks which characters need bold tags. Consecutive true values are merged into single tag pairs, handling overlapping matches automatically. TutorialsPoint - Add Bold Tag in String | Optimized with HashSet
Asked in
Google 15 Facebook 12 Amazon 8
28.4K Views
Medium Frequency
~25 min Avg. Time
856 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