Ctrl K

Highlight Search Hits

Medium
A search engine highlights every spot in a snippet where a query word appears. You are given a string text and a list of keywords keywords. Wrap every occurrence of any keyword in text (occurrences may overlap) in <b> and </b> tags. To keep the markup clean, highlighted pieces that overlap or touch each other are merged under a single pair of tags. Return text with the tags in place. Letter case matters.
Example 1
text='redcarandbluecar', keywords=['car', 'blue'] → 'red<b>car</b>and<b>bluecar</b>'

car occurs twice and blue once. The second car sits right after blue, so the two are wrapped in a single pair of tags.

Example 2
text='aaaba', keywords=['aa', 'ab'] → '<b>aaab</b>a'

aa occurs at positions 0 and 1 (the hits overlap) and ab at position 2. Together they cover characters 0–3 as one block; the final a stays plain.

Example 3
text='Report2024', keywords=['report', '2025'] → 'Report2024'

Case matters, and 2025 is not in the text, so nothing gets highlighted.

Constraints
  • 1 ≤ len(text) ≤ 1000
  • 0 ≤ len(keywords) ≤ 100
  • 1 ≤ len(keywords[i]) ≤ 1000
  • text and keywords[i] consist of English letters and digits
  • All keywords are distinct
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsHighlight Search Terms MediumSplit Into Dictionary Words MediumShorten Words to Their Roots MediumMost Searched Words MediumWord Grown Letter by Letter Medium
loading Python…
Input
text='redcarandbluecar', keywords=['car', 'blue']
Expected
'red<b>car</b>and<b>bluecar</b>'

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