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 dictionarysentence
Example 1
Output: "the cat was rat by the bat"
Example 2
Output: "a a b c"
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").
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)
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 Nodenextnull
Second, whether a root word ends at this node, kept in a flag named isRoot
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
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 Solution
The method replaceWords
- First, build the trie. Create the start node,
, as a newtrie . A loop goes over the roots inNode , and for each root a pointer nameddictionary starts atcur .trie - Inside, a second loop reads the root's letters. Each letter
gives its array position,ch . If that link is missing, create a new node there, then moveslot = ch - 'a' to it. After the root's last letter, setcur .cur.isRoot = true - Next, split the sentence with
and loop over the words. Asentence.split(" ") namedStringBuilder collects the answer, and a space goes in before each word unlesssb is still empty.sb - For each word, add the result of a helper method,
, which returns the word's shortest root, or the word itself when no root fits. Inside the helper,shortestRoot(trie, word) starts atcur and a loop moves it one link per letter, withtrie as the letter's position in the word.i - In that loop, a
link returns the whole word. A node withnull set returnsisRoot , the letters read so far. If the loop ends without either, the word ran out first, and the helper returns the whole word.word.substring(0, i + 1) - When every word is added, return
.sb.toString()
The main
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:
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 bata a b c
Look at the third line: ca
The fourth line, cat cats catchisRoot
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
read each sentence letter at most once.StringBuilder - Space: O(D + S), because the trie has at most one node per root letter, each with 26 links, and the words from
and the answer each hold at most S letters.split
How a trie inserts and searches whole words is covered in