SDE & MLE Prep

648. Replace Words

Problem

Replace every word of sentence that starts with one of the dictionary roots by the shortest such root; other words stay unchanged.

Example: dictionary = ["cat","bat","rat"], sentence = "the cattle was rattled by the battery" → "the cat was rat by the bat"

Insert the roots into a trie. For each word, walk the trie and stop at the first end-of-root marker; replace the word with that prefix.

Complexity: O(total characters).

class Solution:
    def replaceWords(self, dictionary: List[str], sentence: str) -> str:
        root = {}
        for w in dictionary:
            node = root
            for ch in w:
                node = node.setdefault(ch, {})
            node["$"] = True

        def shortest(word):
            node = root
            for i, ch in enumerate(word):
                if ch not in node:
                    return word
                node = node[ch]
                if "$" in node:
                    return word[:i + 1]
            return word

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