← Questions
Add bold tags around matching substrings
0
I was asked this
No reports yet. Sign in to say where you were asked it.
A coding interview question asked in Apple's coding round, last asked Mar 2026. It tests strings and intervals.
Given a string text and a list of patterns, return text with every occurrence of any pattern wrapped in <b> and </b>. Matches that overlap or touch share one pair of tags, so the output uses as few tag pairs as possible.
Interface
Unless you agree on a different interface with the interviewer, assume:
add_bold_tags(text: str, patterns: list[str]) -> str
Example
add_bold_tags("abcxyz123", ["abc", "123"]) -> "<b>abc</b>xyz<b>123</b>"
add_bold_tags("aaabbcc", ["aaa", "aab", "bc"]) -> "<b>aaabbc</b>c" # aaa and aab overlap, bc touches them
add_bold_tags("abab", ["ab"]) -> "<b>abab</b>" # two adjacent matches merge
Constraints
-
0 <= len(text) <= 1000. -
0 <= len(patterns) <= 100; each pattern has 1 to 100 characters. -
textand the patterns are lowercase English letters.
Clarifying questions
- Do overlapping and adjacent matches both merge?
- Is matching case-sensitive?
- Can the pattern list contain duplicates or the empty string?
- Should text that already contains tags be escaped?
What a strong answer covers
- Mark every character covered by at least one match (a boolean array), or collect match intervals and merge them; then build the output in one left-to-right pass.
- A simpler scan: at each position track the furthest end of any match starting at or before it.
- Cost: naive matching is
O(len(text) · total pattern length); a trie or Aho-Corasick finds all matches in about linear time. - Edge cases: empty text, no patterns, a match at the very end, one pattern inside another, a match covering the whole string.
Follow-ups
- Make matching fast for thousands of patterns.
- Support case-insensitive matching while keeping the original case in the output.
- Patterns now have priorities and different tags (
<b>,<i>): how do nested or crossing ranges work?
Where it's asked
- Apple · Coding · Last asked Mar 2026
What it tests
No official answer yet. Write yours on the right and run it.
Nothing published yet.
Sign in to submit your code; every attempt is kept here.
Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding
