KatInterview

Mask the Leftmost Longest Keyword in a Text

StringsAuto-graded · 20 test cases
MediumAuto-gradedStringsstringsstring-matchingsimulation

Last 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

  1. Look at every position in text where at least one keyword occurs as a contiguous substring starting at that position.
  2. Choose the smallest such starting index. The order of keywords in the list has no influence on this choice.
  3. If several keywords start at that chosen index, pick the longest one.
  4. 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 text has no matches, so the result is the empty string.

Constraints

  • 0 <= len(text) <= 1000
  • 1 <= len(keywords) <= 50
  • 1 <= len(keyword) <= 20 for 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.