Problem 469261 · medium · Level 04 Non-Linear Data Structures

Trimming Words Back to Their Stems

trie · strings

A note-taker saves time by cutting long words back to stems she already knows. Given the stems roots and a sentence whose words are separated by single spaces, replace each word that begins with some stem by the shortest stem it begins with. A word that begins with no stem is left as it is. Return the shortened sentence.

Examples

Input:  roots = ["sun", "rain", "snow"], sentence = "the sunflower and rainbow made snowmen smile"
Output: "the sun and rain made snow smile"

Input:  roots = ["a", "aa"], sentence = "aaa aab b"
Output: "a a b"

Constraints

  • 0 <= len(roots) <= 10**4, roots are non-empty lowercase strings
  • sentence contains up to 10**4 words of lowercase letters; it may be empty
  • Target: O(total root characters + total sentence characters)

Goals

  • Stop a trie walk as soon as a stored word ends
  • Rebuild a sentence word by word
Starting Python…