Shorten Words to Their Stems

Medium · Tries & String Matching · about 20 min

A search index stores words by their stem. You get a list of stems and a sentence of lowercase words separated by single spaces.

Replace every word that starts with at least one stem by the shortest such stem. Words that start with no stem stay unchanged. Return the new sentence with single spaces.

  • Stems are non-empty lowercase words. The sentence may be empty (return "").

Examples:

stem_sentence(["run", "jump", "walk"], "runner jumped and walked home") → "run jump and walk home"

stem_sentence(["ab", "a"], "abc") → "a" (the shortest stem wins, not the first one listed)

Hints

  • Insert every stem into a trie and mark the node where each stem ends.
  • For each word, walk the trie along its letters. The first stem-end marker you reach is the shortest stem.
  • If a letter is missing before you reach a marker, keep the whole word.

Learn the pattern first: the Tries & String Matching lesson.

More Tries & String Matching problems