Mask the Leftmost Longest Keyword in a Text
StringsAuto-graded · 20 test casesLast updated
Find the earliest-starting match among several keywords, prefer the longest at that spot, and collapse it into a single placeholder character.
Mask the Leftmost Longest Keyword
You are given a text string text and a list of keywords keywords. Your task is to mask exactly one keyword occurrence inside text and return the new string.
Selection rules
- Look at every position in
textwhere at least one keyword occurs as a contiguous substring starting at that position. - Choose the smallest such starting index. The order of keywords in the list has no influence on this choice.
- If several keywords start at that chosen index, pick the longest one.
- Replace the entire chosen occurrence (all of its characters) with a single character
"?".
Only one replacement is performed. Everything before and after the occurrence remains unchanged. If no keyword occurs anywhere in text, return text unchanged.
Details
- Matching is case-sensitive and uses exact substring comparison.
- Keywords may overlap with each other, and one keyword may be a prefix of another.
- Keywords may repeat in the list; duplicates do not change the result.
- An empty
texthas no matches, so the result is the empty string.
Constraints
0 <= len(text) <= 10001 <= len(keywords) <= 501 <= len(keyword) <= 20for each keyword- The replacement character is always
"?".
Examples
Example 1
Input: mask_first_keyword('abccde', ['bc', 'bcc'])
Output: 'a?de'
Example 2
Input: mask_first_keyword('hello world', ['world', 'hello'])
Output: '? world'
Hints
Hint 1
The word 'first' refers to the smallest starting index inside the text, not to the position of the keyword in the list.
Hint 2
Walk through the start indices of the text from left to right. At each index, test every keyword for a match there, and remember the longest one that matches.
Hint 3
As soon as some index has at least one match, nothing later can beat it, so you can build the answer right away from the text before the match, a single '?', and the text after the match. Use startswith with an offset to avoid manual bounds checks.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The rules give a clear priority: the earliest starting index matters most, and keyword length only breaks ties at that index. That suggests scanning start positions from left to right.
For each start index, check every keyword with text.startswith(kw, start), which safely returns False when the keyword would run past the end of the text. Track the longest keyword that matches at that index. The first index where any keyword matches is the answer position, because all earlier indices were checked and had no match. Then build the result as text[:start] + "?" + text[start + len(best):] and return immediately.
If the loop finishes with no match, return text unchanged. This also covers the empty-text case, since the loop does not run.
Why it is correct
- Earliest start: indices are visited in increasing order, and we stop at the first one with a match, so no earlier match exists.
- Longest at that start: every keyword is tested at that index, and the best is replaced only by a strictly longer match. Two matching keywords of equal length at the same index are the same substring, so the output is identical either way.
- Replacement: the prefix and suffix are kept intact and the matched span becomes one
"?".
Complexity
Let n = len(text), m = len(keywords), and L the maximum keyword length.
- Time: O(n * m * L) in the worst case, at most about 10^6 character comparisons under the given limits.
- Space: O(n) for the output string, with O(1) extra working space.
(For a very large keyword set, a trie walked from each start index would reduce the cost to O(n * L).)
Reference solution
from typing import List
def mask_first_keyword(text: str, keywords: List[str]) -> str:
for start in range(len(text)):
best = None
for kw in keywords:
if text.startswith(kw, start):
if best is None or len(kw) > len(best):
best = kw
if best is not None:
return text[:start] + "?" + text[start + len(best):]
return text