Start learning free

LESSON 504 OF 673 · TRIES

Replace Words in Python: O(S) Time with a Trie

Practice O(S) Read the full explanation

You get a list of strings roots and a string sentence. The words of sentence are separated by single spaces.

Return the sentence after replacing each word that starts with a root by that root.

If a word starts with more than one root, use the shortest one. A root can also be the whole word. Words that start with no root stay as they are.

 

Example 1:

Input: roots = ["sun","snow"], sentence = "sunny days and snowy nights"
Output: "sun days and snow nights"
Explanation: "sunny" starts with "sun".
"snowy" starts with "snow".
The other words start with no root.

Example 2:

Input: roots = ["book","bookworm"], sentence = "bookworms read books"
Output: "book read book"
Explanation: "bookworms" starts with "book" and with "bookworm".
The shorter root, "book", wins.
"books" becomes "book" too.

Example 3:

Input: roots = ["moon"], sentence = "mo moonlight moon"
Output: "mo moon moon"
Explanation: "mo" is shorter than the root, so it stays.
"moonlight" starts with "moon".
The last word is the root itself.

 

Constraints:

  • 1 to 1,000 roots.
  • Each root has 1 to 100 letters.
  • sentence has 1 to 10,000 words.
  • Each word has 1 to 100 letters.
  • Every letter is from a to z.
  • One space separates each two words.
  • There are no spaces at the start or the end.

Note:

Your solution should run in O(S) time. S is the total number of letters in roots and sentence.



Put the roots in a trie, and mark the node where each root ends.

For each word, walk down the trie letter by letter. The first node where a root ends gives the shortest root. If the trie has no path for the next letter, or the word ends first, keep the word.

Building the trie visits each letter of the roots once. Each walk is at most as long as its word: O(S) time.
The trie and the new sentence take O(S) extra space.
STEP 1 OF 18
    Ctrl + Enter to check

    PYTHON · TRIES

    Replace Words in Python, explained

    Problem overview

    The method replaceWords receives a list of strings, roots, and a string, sentence, whose words are separated by single spaces. It returns the sentence after replacing each word that starts with a root by that root. If a word starts with several roots, the shortest one wins. A root can also be the whole word, and a word that starts with no root stays as it is. All letters are from a to z, and the sentence has no spaces at the start or the end.

    With roots = ["sun", "snow"] and sentence = "sunny days and snowy nights", the result is "sun days and snow nights": sunny starts with sun, snowy starts with snow, and the other words start with no root. With roots = ["book", "bookworm"] and "bookworms read books", the word bookworms starts with both roots, the shorter book wins, and the result is "book read book". With roots = ["moon"], the word mo is shorter than the root and stays: "mo moonlight moon" becomes "mo moon moon".

    The statement asks for O(S) time, where S is the total number of letters in roots and sentence.

    Approach: a trie of the roots

    The direct way checks every word against every root with startswith. With up to 1,000 roots and 10,000 words, that is millions of comparisons, and each one can read up to 100 letters. A trie avoids it.

    A trie is a tree with one node per prefix. The root of the tree is the empty prefix, each edge is one letter, and roots that start the same way share the same path. Put every root in the trie and mark the node where each root ends. Then one walk down the trie along a word meets, in order of length, every root the word starts with. The first marked node on the way is the shortest root, so the walk can stop there.

    The walk ends in one of three ways: it reaches a marked node (replace the word by the letters walked), the word runs out of letters first, or the next letter has no child in the trie. In the last two cases no root is a prefix of the word, and the word is kept.

    Step by step

    1. Design the node. In TrieNode.__init__, self.children is an empty dict from a letter to the child node, and self.isEnd is False. The flag becomes True where a root ends. In the second example, the node for book sits in the middle of the path to bookworm, and only the flag says that a root ends there.
    2. Create the top node. It is called trie, because the name root is taken by the roots being inserted.
    3. Insert every root. For each root, start node at trie. For each letter c, create a child under c if it isn't in node.children, then move node to the child. After the letters, set node.isEnd = True.
    4. Prepare the output. result is an empty list that collects one new word for each word of the sentence.
    5. Split the sentence. sentence.split(" ") cuts it at each space and gives the list of words.
    6. Start each walk. For each word, node starts at trie and length at 0. The variable counts the letters walked, which is also the length of the root found, if any.
    7. Walk. The loop runs while three things hold: no root ends at node (not node.isEnd), length < len(word), and word[length] in node.children. Inside it, move node to node.children[word[length]] and add 1 to length. The order of the tests matters, as explained below.
    8. Choose what to append. If node.isEnd is True, append word[:length]. Otherwise append the whole word.
    9. Join the result. " ".join(result) puts one space between each two words and none at the ends.

    The solution in Python

    class TrieNode:
        def __init__(self):
            self.children = {}
            self.isEnd = False
    
    
    class Solution:
        def replaceWords(self, roots: List[str], sentence: str) -> str:
            trie = TrieNode()
            for root in roots:
                node = trie
                for c in root:
                    if c not in node.children:
                        node.children[c] = TrieNode()
                    node = node.children[c]
                node.isEnd = True
            result = []
            for word in sentence.split(" "):
                node = trie
                length = 0
                while not node.isEnd and length < len(word) and word[length] in node.children:
                    node = node.children[word[length]]
                    length += 1
                if node.isEnd:
                    result.append(word[:length])
                else:
                    result.append(word)
            return " ".join(result)
    

    Python details worth noting:

    • and stops at the first false part. This is called short-circuit evaluation. Because length < len(word) comes before word[length], the index is only read when it exists. Reading word[2] from "mo" raises IndexError: string index out of range, so swapping the two tests would break the word that runs out of letters.
    • in on a dict looks at keys. word[length] in node.children asks whether a child exists for that letter, in constant time on average.
    • Slicing a string. word[:length] is the first length letters as a new string. Strings are immutable, so word itself doesn't change.
    • split(" ") and split(). With one explicit space, two spaces in a row would produce an empty string between them. The statement promises single spaces, so split(" ") returns exactly the words, and " ".join restores the sentence. split() with no argument would also work here.
    • Building then joining. Appending to a list and calling " ".join(result) is the idiomatic way to build a string from pieces. Adding to a string in a loop would copy the string again on each step.

    A run of the solution

    ['sun', 'snow'] 'sunny days and snowy nights' -> 'sun days and snow nights'
    ['book', 'bookworm'] 'bookworms read books' -> 'book read book'
    ['moon'] 'mo moonlight moon' -> 'mo moon moon'
    ['a'] 'apple' -> 'a'
    ['cat', 'bat'] 'dog' -> 'dog'
    ['abc', 'a'] 'abcd a ab' -> 'a a a'
    

    The last example has the roots in the order ["abc", "a"]. The word abcd becomes a, not abc: the order of the roots in the list doesn't matter, because the walk always stops at the shortest root.

    Complexity

    Time: O(S). Building the trie reads each letter of the roots once. The walk for a word takes at most as many steps as the word has letters, so all the walks together read each letter of the sentence at most once. Splitting and joining are also linear in the sentence.

    Space: O(S). The trie has at most one node per letter of the roots, plus the top node. The list result and the final string are no longer than the sentence.

    Edge cases and common mistakes

    • The word is the root. In "mo moonlight moon", the last word is exactly the root. The walk reaches the marked node after the last letter, and the answer is the word itself.
    • The word is shorter than the root. mo never reaches a marked node. The loop stops because the word ran out, node.isEnd is False, and the word is kept.
    • Several roots on the same path. Stopping at the first marked node gives the shortest root. A version that keeps walking and remembers the last marked node would give the longest, bookworm where the statement wants book.
    • A partial path. With the root moon, the word moose follows m, o, o, then finds no child for s. No root ends on the way, so the word is kept. Replacing it by the letters walked so far (moo) would be a mistake: the replacement is only valid at a marked node.
    • Reading the letter before checking the length. The test word[length] in node.children must come after length < len(word), or short words raise IndexError.
    • Replacing words that don't start with a root. A root in the middle of a word doesn't count: only prefixes do.
    • Forgetting to restart at the top. node and length are reset for every word. If they were set once before the loop, the second word would continue from where the first stopped.
    Keep going with Python650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free