Replace Words

Shorten every word of a sentence to the shortest dictionary root it starts with, using a trie.

Given a list of short words called roots, the dictionary, and a sentence of lowercase words separated by single spaces, replace every word that starts with a root by that root. If several roots fit a word, use the shortest one. Words that start with no root stay as they are.

Example 1
Input: dictionary = ["cat","bat","rat"], sentence = "the cattle was rattled by the battery"
Output: "the cat was rat by the bat"
Example 2
Input: dictionary = ["a","b","c"], sentence = "aadsfasf absbs bbab cadsfafs"
Output: "a a b c"
Solution

The Idea

Many longer words grow out of a shorter one: "cattle" begins with "cat", and "battery" begins with "bat". Here the short words are given in the dictionary, and each longer word in the sentence is cut back to the root it begins with.

Walk through Example 1 one word at a time. The word "the" begins with none of "cat", "bat" or "rat", so it stays. Next, "cattle" begins with "cat" and becomes "cat". Then "rattled" becomes "rat", "by" stays, and "battery" becomes "bat". The answer is "the cat was rat by the bat".

For each word, then, we need the roots it begins with. Testing every root against every word works, but it repeats itself: a word is checked against "cat" from its first letter, then against "bat" from its first letter again, and so on. Could the roots be stored so that one pass over a word's letters finds its root?

Look at the picture below. At the top is the start node. Each link going down carries one letter, and following links spells a word. From the start node, the link c leads to a node, its link a to the next, and its link t to a node marked with a tick. So the path c, a, t spells "cat", and the tick says a root word ends here. The links b and r spell "bat" and "rat" the same way. A tree of letters like this, where words with the same first letters share the same path, is called a trie (from retrieval, often said like "try").

The trie for the roots cat, bat and rat. From the start node, links c, b and r each lead on to a and then t, where a root word ends. Walking cattle follows c, a, t and stops at the first word end, so cattle becomes cat. The start node has no link t, so the stays as it is.

Now walk "cattle" through it, letter by letter, along the orange path. The c, a and t links all exist, and the node after t is marked as a root word end. The walk can stop right there: the word becomes "cat", and its last three letters, t, l and e, are never read. On the right, the part labelled walking "the" shows that the start node has no link t, so "the" stays as it is.

Why does stopping at the first tick give the shortest root? Every root that "cattle" begins with lies on this one path, and a shorter root ends higher up. So the first tick met is the shortest root. In Example 2 the root "a" ends right below the start node, so "aadsfasf" is cut back to "a" after one letter.

Solution Approach

Testing every root against every word would already work, and the trie version improves on it with three decisions: what a trie node holds, how one word walks the trie, and how the new sentence is put together.

Testing every root against every word

Why not loop over the dictionary for each word and check word.startsWith(root)? It gives the right answer, as long as it keeps the shortest match. But it cannot stop at the first match, because a shorter root may come later in the list. So every word is compared with every root, and with a large dictionary that is the bulk of the work. The trie needs at most one step per letter of the word, however many roots there are.

What a trie node holds

What does each node in the picture need to know? In the code a node is an object of a small class named Node, and it needs two things. First, where each letter leads. The words have only the 26 letters a to z, so a node keeps an array of 26 links, named next, where slot 0 is for a, slot 1 for b, and so on. A missing link is null.

Second, whether a root word ends at this node, kept in a flag named isRoot. A path alone is not enough. With the single root "catch", the word "cat" goes along c, a, t, yet no root ends there, so "cat" must stay as it is.

Walking one word

How can a walk end? It follows the word's letters from the start node, and one of three things happens. The next link is missing, so no root begins this way and the word stays. Or the walk reaches a node with isRoot set, and the letters read so far are the shortest root. Or the word runs out first, as "cat" does with the root "catch", and the word stays.

Putting the sentence back together

How is the answer built? Split the sentence at the spaces, replace each word, and join the results with single spaces. A StringBuilder, Java's growable string, collects them. Adding a space before every word except the first leaves no extra space at the end to trim.

Java Solution

The method replaceWords works in these steps:

  1. First, build the trie. Create the start node, trie, as a new Node. A loop goes over the roots in dictionary, and for each root a pointer named cur starts at trie.
  2. Inside, a second loop reads the root's letters. Each letter ch gives its array position, slot = ch - 'a'. If that link is missing, create a new node there, then move cur to it. After the root's last letter, set cur.isRoot = true.
  3. Next, split the sentence with sentence.split(" ") and loop over the words. A StringBuilder named sb collects the answer, and a space goes in before each word unless sb is still empty.
  4. For each word, add the result of a helper method, shortestRoot(trie, word), which returns the word's shortest root, or the word itself when no root fits. Inside the helper, cur starts at trie and a loop moves it one link per letter, with i as the letter's position in the word.
  5. In that loop, a null link returns the whole word. A node with isRoot set returns word.substring(0, i + 1), the letters read so far. If the loop ends without either, the word ran out first, and the helper returns the whole word.
  6. When every word is added, return sb.toString().

The main method runs both examples, then the roots "cat" and "ca" with the word "cattle", the root "catch" with words shorter and longer than it, and a dictionary that fits no word.

Java
import java.util.List;

public class ReplaceWords {

    private static class Node {
        Node[] next = new Node[26];   // one slot per letter, a to z
        boolean isRoot;               // a dictionary root ends here
    }

    public static String replaceWords(List<String> dictionary, String sentence) {
        Node trie = new Node();
        for (String root : dictionary) {
            Node cur = trie;
            for (char ch : root.toCharArray()) {
                int slot = ch - 'a';
                if (cur.next[slot] == null) {
                    cur.next[slot] = new Node();
                }
                cur = cur.next[slot];
            }
            cur.isRoot = true;
        }

        StringBuilder sb = new StringBuilder();
        for (String word : sentence.split(" ")) {
            if (sb.length() > 0) {
                sb.append(' ');
            }
            sb.append(shortestRoot(trie, word));
        }
        return sb.toString();
    }

    // Walks the word through the trie and stops at the first root it meets.
    private static String shortestRoot(Node trie, String word) {
        Node cur = trie;
        for (int i = 0; i < word.length(); i++) {
            cur = cur.next[word.charAt(i) - 'a'];
            if (cur == null) {
                return word;                      // no root starts this way
            }
            if (cur.isRoot) {
                return word.substring(0, i + 1);  // shortest root found
            }
        }
        return word;                              // the word ended before any root did
    }

    public static void main(String[] args) {
        System.out.println(replaceWords(List.of("cat", "bat", "rat"),
                "the cattle was rattled by the battery"));
        System.out.println(replaceWords(List.of("a", "b", "c"),
                "aadsfasf absbs bbab cadsfafs"));
        System.out.println(replaceWords(List.of("cat", "ca"), "cattle"));
        System.out.println(replaceWords(List.of("catch"), "cat cats catcher"));
        System.out.println(replaceWords(List.of("dog"), "the cattle was rattled"));
    }
}

Running it prints:

Output
the cat was rat by the bat
a a b c
ca
cat cats catch
the cattle was rattled

The first line, the cat was rat by the bat, is the walk from the picture repeated for every word of Example 1, and a a b c matches Example 2.

Look at the third line: ca. The dictionary lists "cat" before "ca", yet "cattle" becomes the shorter one. Both roots lie on the path c, a, t, and the walk meets the end of "ca" one node before the end of "cat", so the order of the list does not matter.

The fourth line, cat cats catch, shows the isRoot flag at work. The words "cat" and "cats" both follow the path toward "catch" but leave it or run out before the h, so no root ends on their way and they stay. The word "catcher" reaches the end of "catch" and is cut back to it. In the last line, the root "dog" fits none of the words, and the sentence comes back unchanged.

Complexity

The work is building the trie once, then one walk per word of the sentence, so the bounds use D, the total number of letters in all the roots, and S, the length of the sentence.

  • Time: O(D + S), because building the trie takes one step per root letter, and each walk, the split and the StringBuilder read each sentence letter at most once.
  • Space: O(D + S), because the trie has at most one node per root letter, each with 26 links, and the words from split and the answer each hold at most S letters.

How a trie inserts and searches whole words is covered in Implement Trie.