Python coding

Shorten words to their shortest root

You get a list roots and a sentence of words separated by single spaces. A word can be shortened to a root when it starts with that root; a word equal to a root counts. Replace every word that has at least one such root with the shortest of them, leave the other words unchanged, and return the new sentence.

Roots and words use lowercase a–z and have at least one letter. roots may be empty or contain repeats; the sentence has at least one word.

Besides the tests, one large input (8,000 roots, 5,000 words) with a ~400 ms limit (scaled to your device's speed): brute force won't pass.

  • shorten(["help","play","re"], "helpful players replayed the game") → "help play re the game"
  • shorten(["sun","su","sunny"], "sunny sunday sugar sand") → "su su su sand"
  • shorten(["x"], "plain words stay") → "plain words stay"
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

Insert every root in a trie and mark the node where each root ends. Then each word is a single walk from the top, one letter per step.

Hint 2

Stop at the first end mark you step on: that prefix is the shortest root. If a letter has no child before any mark, the word has no root: keep it whole.

Solution and why it works
pythonO(R + S), R = letters in roots, S = letters in the sentence · O(R) for the trie
def shorten(roots: list[str], sentence: str) -> str:
    trie = {}
    for root in roots:
        node = trie
        for ch in root:
            node = node.setdefault(ch, {})
        node["$"] = True                 # a whole root ends here

    def shortest_root(word: str) -> str:
        node = trie
        for i, ch in enumerate(word):
            if ch not in node:
                break                    # no root continues along this word
            node = node[ch]
            if "$" in node:
                return word[:i + 1]      # first end mark on the way down = shortest root
        return word

    return " ".join(shortest_root(w) for w in sentence.split(" "))

A trie stores all the roots along shared paths, so one walk down it compares a word against every root at once: O(length of the word), however many roots there are. The first end mark reached is the shortest root, because every shorter prefix was passed without one. Traps: without end marks, a word that only shares its first letters with a root gets cut too ("cat" → "ca" under the root "cart"); and walking on past the first mark returns the longest root, not the shortest.