Start learning free

LESSON 221 OF 314 · TRIES

Replace Words in Swift: Shortest Root with a Trie

Practice O(S) Read the full explanation

You get an array 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 19
    Ctrl + Enter to check

    SWIFT · TRIES

    Replace Words in Swift, explained

    Problem overview

    The method replaceWords receives an array of strings roots and a string sentence whose words are separated by single spaces. It returns the sentence after each word that starts with a root has been replaced by that root. If a word starts with several roots, the shortest wins. A root can also be the whole word, and a word that starts with no root stays unchanged.

    With roots = ["sun", "snow"] and the sentence "sunny days and snowy nights", the result is "sun days and snow nights". With roots = ["book", "bookworm"] and "bookworms read books", the word bookworms starts with both roots, and the shorter one, book, is used: the result is "book read book". With roots = ["moon"], the word mo in "mo moonlight moon" is shorter than the root, so it stays: "mo moon moon".

    Approach: put the roots in a trie

    For one word, the brute-force way is to test every root with a prefix check and keep the shortest match. With up to 1,000 roots and up to 10,000 words, that repeats a lot of work. A trie answers the question for all roots at once.

    A trie is a tree with one node per prefix. Roots that start the same way share a path from the top node. Each node has a dictionary from the next letter to the child node, and an isEnd flag that is true where some root ends. Walking down the trie along a word passes through every root the word starts with, in order of length, because a shorter root ends higher on the path.

    So the walk for a word can stop at the first node where isEnd is true: that is the shortest root. The walk also stops when the word runs out of letters, or when the trie has no child for the next letter. In both cases no root fits, and the word is kept as it is.

    The flag is needed because a root can be a prefix of a longer root. In the second example the node for book is in the middle of the path to bookworm. Only the flag says that a root ends there.

    Step by step

    1. Add the children dictionary to TrieNode: [Character: TrieNode], starting as [:]. Looping over a String gives characters, so they are the keys.
    2. Add var isEnd = false, set to true where a root ends.
    3. Create the top node, trie, as a let. It always refers to the same node. The name root is left for the loop variable that holds each root.
    4. Loop over the roots to insert each one.
    5. Start a var node at trie, because every root is inserted from the top.
    6. Loop over the characters of the root. Each one goes one level down.
    7. Create the child if it is missing. A dictionary lookup for a missing key gives nil.
    8. Move node to the child with node.children[c]!. The lookup is an optional, and the ! is safe because the if made sure the child exists.
    9. Mark the end with node.isEnd = true, after the inner loop and inside the outer one.
    10. Create var result = [String]() to collect the new words.
    11. Loop over sentence.split(separator: " "). Each piece is a Substring, a view into the sentence.
    12. Convert the word to an array: let letters = Array(word). A string cannot be read at an integer position in Swift, but an array of characters can.
    13. Start a var node at trie for this word.
    14. Start var length = 0. It counts the letters walked, which is also the length of the root once one is found.
    15. Write the loop condition: no root ends at node (!node.isEnd), length < letters.count, and node.children[letters[length]] != nil. The conditions are joined with &&, which stops at the first false part, so the length is checked before the letter at that index is read.
    16. Move down one level in the loop body and add 1 to length.
    17. If node.isEnd is true, append the root, which is the first length letters of the word: String(word.prefix(length)).
    18. Otherwise append the whole word, String(word).
    19. Join the words with single spaces: result.joined(separator: " ").

    The solution in Swift

    class TrieNode {
        var children: [Character: TrieNode] = [:]
        var isEnd = false
    }
    
    class Solution {
        func replaceWords(_ roots: [String], _ sentence: String) -> String {
            let trie = TrieNode()
            for root in roots {
                var node = trie
                for c in root {
                    if node.children[c] == nil {
                        node.children[c] = TrieNode()
                    }
                    node = node.children[c]!
                }
                node.isEnd = true
            }
            var result = [String]()
            for word in sentence.split(separator: " ") {
                let letters = Array(word)
                var node = trie
                var length = 0
                while !node.isEnd && length < letters.count && node.children[letters[length]] != nil {
                    node = node.children[letters[length]]!
                    length += 1
                }
                if node.isEnd {
                    result.append(String(word.prefix(length)))
                } else {
                    result.append(String(word))
                }
            }
            return result.joined(separator: " ")
        }
    }

    Swift details worth knowing:

    • split(separator: " ") returns an array of Substring values. They share storage with sentence, so the solution wraps them in String(...) before adding them to an array of String.
    • TrieNode is a class, so var node = trie is another name for the same object. Changes made through node change the trie.
    • When the walk ends because of the word, node.isEnd is checked, not the other conditions. If the loop ended at a node where a root ends, that node is the answer. If it ended for any other reason, node.isEnd is false: the loop only continues while the flag is false, so it can't have moved past a node with the flag set.

    Complexity

    Let S be the total number of letters in the roots and in the sentence. Building the trie visits each root letter once. Each word's walk is at most as long as the word, so all the walks together cost at most the length of the sentence. The time is O(S). The trie and the result take O(S) extra space.

    Edge cases and common mistakes

    • A word shorter than a root. The walk runs out of letters before reaching a flagged node, so the word stays: mo against moon.
    • The word equals a root. The walk reaches the flag on the last letter, and the root is the word itself.
    • Several roots fit. Stopping at the first flag gives the shortest. Continuing to the deepest flag would give the longest, which is wrong here: catalog with roots cat and catalog becomes cat.
    • A partial match. A word can follow part of a root's path without reaching its end. With the root moon, the word moose shares moo with it but never reaches the flag, so it stays. Checking the flag at the end is what avoids cutting such a word.
    • Reading past the end of the word. Putting length < letters.count after the dictionary lookup would index outside the array and crash. Keep the order of the conditions.
    • Returning substrings. Appending a Substring to a [String] does not compile; convert with String(...).

    Testing

    Results from the solution above:

    rootssentenceResult
    ["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", "b"]"cat bat rat""cat b rat"
    ["cat", "catalog"]"catalog cattle cat ca""cat cat cat ca"
    ["x"]"hello""hello"
    Keep going with Swift1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free