Wrap Matching Substrings in Bold Tags
Company: Apple
Role: Machine Learning Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Onsite
Quick Answer: This question evaluates string manipulation, pattern matching, and interval-merging competency within algorithmic problem-solving for text processing and HTML-like formatting.
Constraints
- 0 <= len(text) <= 1000
- 0 <= len(patterns) <= 100
- 1 <= len(patterns[i]) <= 100 for each pattern that exists
- Both `text` and `patterns[i]` consist of lowercase English letters
Examples
Input: ("abcxyz123", ["abc", "123"])
Expected Output: "<b>abc</b>xyz<b>123</b>"
Explanation: The matches are `abc` and `123`, and they are separate, so they become two bold segments.
Input: ("aaabbcc", ["aaa", "aab", "bc"])
Expected Output: "<b>aaabbc</b>c"
Explanation: `aaa` and `aab` overlap near the start, and `bc` touches that merged region, so all matched characters from index 0 to 5 are wrapped together.
Input: ("ababcd", ["ab", "abc", "bcd"])
Expected Output: "<b>ababcd</b>"
Explanation: The matches overlap and connect across the whole string, so a single pair of tags wraps everything.
Input: ("hello", [])
Expected Output: "hello"
Explanation: With no patterns, nothing is bolded.
Input: ("", ["a", "bc"])
Expected Output: ""
Explanation: An empty text produces an empty result.
Input: ("a", ["a", "aa"])
Expected Output: "<b>a</b>"
Explanation: The single character matches `a`, so the whole string is bolded.
Input: ("abcdef", ["gh", "ij"])
Expected Output: "abcdef"
Explanation: None of the patterns appear in the text, so the output is unchanged.
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.