progress

~/problems / Tries

Substring Wrapper

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

easy ~15 min Meta Uber

A search page highlights keywords inside the words of a query. You get a sentence s (words separated by single spaces) and a list of keywords elements.

Implement wrap_words(s: str, elements: list[str]) -> str. For each word on its own:

  • Find the keyword occurrence with the smallest start index; on a tie, take the longest keyword.
  • Put [ before it and ] after it. Only that one occurrence is bracketed.
  • A word with no keyword is left unchanged.

Return the words joined with single spaces. Matching is case-sensitive; keywords are non-empty and may repeat.

wrap_words("banana split", ["an", "nan", "lit"])
# "b[an]ana sp[lit]"        "an" starts at index 1, before "nan" at index 2
wrap_words("seesaw", ["s", "see", "saw"])
# "[see]saw"                 "s" and "see" both start at 0: the longer wins
wrap_words("hello world", ["xyz"])
# "hello world"
wrap_words("", ["a"])
# ""

⭐ Bonus: a speed test with 20,000 words and 5,000 keywords (up to 20 letters) earns a star in about O(len(s) × longest keyword), instead of checking every keyword against every word.

Show hint

Put the keywords in a trie. From each start index, walk the trie along the word and remember the deepest node that ends a keyword.

Topic: Trie. Prefix tree; longest-match tokenizing.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc