Coding questions · Apple
Wrap Matching Substrings in Bold Tags
This question evaluates string manipulation, pattern matching, and interval-merging competency within algorithmic problem-solving for text processing and HTML-like formatting.
During a machine learning engineer phone screen, the coding task was:
You are given a string text and a list of strings patterns. Return a new string where every substring of text that matches any string in patterns is wrapped in HTML-style bold tags: <b> and </b>.
Rules:
- If two matched ranges overlap, they must be merged into one bold segment.
- If two matched ranges are adjacent, they should also be merged into one bold segment.
- The output should contain the minimum number of bold tag pairs needed to cover all matches.
Example 1:
- Input:
text = "abcxyz123",patterns = ["abc", "123"] - Output:
"<b>abc</b>xyz<b>123</b>"
Example 2:
- Input:
text = "aaabbcc",patterns = ["aaa", "aab", "bc"] - Output:
"<b>aaabbc</b>c"
Implement a function that returns the formatted string.
Wrap Matching Substrings in Bold Tags
Constraints
- 0 <= len(text) <= 1000
- 0 <= len(patterns) <= 100
- 1 <= len(patterns[i]) <= 100 for each pattern that exists
- Both
textandpatterns[i]consist of lowercase English letters
Hints
- Try marking which character positions belong to at least one matched pattern, then build the answer from those marks.
- While scanning from left to right, keep track of the furthest end index of any pattern that starts at or before the current position.