Ctrl K

Highlight Search Terms

Medium
A search engine highlights the matched words in a text. You are given a list of keywords keywords and a string text. Every character of text that belongs to at least one occurrence of some keyword must end up between the tags <b> and </b>. Occurrences may overlap. Use as few tags as possible: highlighted pieces that overlap or sit right next to each other must be merged into a single piece with one pair of tags. Characters outside every occurrence stay outside the tags. Return the resulting string.
Example 1
keywords=["sun", "set"], text="sunset over the sea" → '<b>sunset</b> over the sea'

The matches of sun and set touch each other, so a single pair of tags covers both.

Example 2
keywords=["ana", "nab"], text="bananabread" → 'b<b>ananab</b>read'

ana occurs at positions 1 and 3, nab at position 4. Together they cover characters 1 through 6, which is one highlighted piece.

Example 3
keywords=["tea"], text="coffee" → 'coffee'

The keyword never occurs, so the text comes back unchanged.

Constraints
  • 1 ≤ len(text) ≤ 500
  • 0 ≤ len(keywords) ≤ 50
  • 1 ≤ len(keywords[i]) ≤ 10
  • text consists of lowercase English letters and spaces; keywords[i] consists of lowercase English letters
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsHighlight Search Hits MediumSplit Into Dictionary Words MediumShorten Words to Their Roots MediumMost Searched Words MediumWord Grown Letter by Letter Medium
loading Python…
Input
keywords=["sun", "set"], text="sunset over the sea"
Expected
'<b>sunset</b> over the sea'

Run checks the first 3 tests in your browser. Submit checks all 132 tests on the server, hidden ones included.