Skip to content
MediumTrieAI interview only

Add Bold Tag in String

Asked atgoogleamazonmetamicrosoft

01 · Problem

You are given a string s and an array of strings words. Every occurrence of any word inside s should be shown in bold.

Mark each character of s that is covered by at least one occurrence of a word. Then wrap every maximal run of marked characters in a single <b> and </b> pair. Overlapping occurrences and occurrences that touch end-to-start must end up inside the same pair of tags. Return the resulting string. If nothing matches, return s unchanged.

02 · Examples

Example 01
Input
s = "hello42world", words = ["hell","world"]
Output
"<b>hell</b>o42<b>world</b>"

"hell" covers indices 0-3 and "world" covers 7-11; the two runs are separated by "o42", so they get separate tags.

Example 02
Input
s = "mmnnop", words = ["mm","mn","nop"]
Output
"<b>mmnnop</b>"

"mm" covers 0-1 and "mn" covers 1-2, so they overlap; "nop" covers 3-5 and touches that run. Everything merges into one bold block.

Example 03
Input
s = "abcdef", words = ["xy","fg"]
Output
"abcdef"

Neither word appears in s, so no tags are added.

03 · Constraints

  • 011 <= s.length <= 1000
  • 021 <= words.length <= 100
  • 031 <= words[i].length <= 1000
  • 04s and words[i] consist of English letters and digits
  • 05All values in words are unique

04 · Optimal complexity

Time
O(n * L + W)
Space
O(n + W)
05 · Two ways to work on it

Practice it alone or rehearse it as an interview.

Practice Mode gives you an editor and test runs, nothing else. AI Interview Mode puts a voice interviewer on the other side, adds a clock, and ends with a scored summary of the round.