Design Add and Search Words Data Structure
Store words in a trie and find them with patterns in which a dot stands for any letter.
Design a class that stores words and looks them up again. It has two methods: addWord(word)search(word)trueword'.'
Example
Output: false, true, true, true
The Idea
You have probably worked on a crossword where some squares of a word are already filled in. A three-letter word ending in "ad" can be written as .ad
Walk through the example. The store holds bad, dad and mad. Searching for padfalsebadtrue.adtrueb..
The simple way is to keep the words in a list and compare the pattern with each one, letter by letter. For pad
It can, if the words are stored letter by letter along paths. Look at the picture below. The circle at the top, labelled root, is where every word starts. Each link below a circle carries one letter, so following the links b, a and d from the root spells bad. The teal circle at the end of that path marks that a stored word ends there.
A tree like this, where each path down from the root spells the start of one or more stored words, is called a trie. Words that begin with the same letters share the same first links. If bat were added to this trie, it would reuse the links b and a and add one new link, t.
Now follow the search for .adtrue
A plain letter, on the other hand, rules out every other link at once. For pad
Solution Approach
Turning the trie into code means settling four things: how a node keeps its links, how a word is added, how a search handles plain letters and dots, and what happens when the pattern runs out.
The links of a node
What does one circle in the picture need to hold? It needs the links that leave it, and a mark that says whether a stored word ends on it. Each circle, called a node, becomes a Node'a'
A slot that is nullbooleanisWord
Adding a word
How does addWordisWord
Searching with dots
What should search
After a link is taken, what is left is the same question on a smaller scale. At the b link, the search for .adadfalse
Going all the way down one path before coming back to try the next link is called depth-first search. The recursion keeps track of where to come back to, so the code needs no list of paths still to try.
The end of the pattern
When the position reaches the end of the pattern, is that a match? Only if a word ends at the current node, so the answer there is isWordtrueba
A pattern longer than every stored word fails on its own. After the last letter of a word there are no links, so the next pattern letter, dot or not, finds every slot empty.
Java Solution
The class has these parts:
: one circle of the trie, withNode , the 26 link slots, andnext , the word-end mark.isWord : the node at the top, created with the object. Every word and every search starts there.root : walks down from the root withaddWord , creates any missing node, and marks the last one withcur .isWord : the public method. It starts the helper at position 0 and the root.search(word) : the helper. It checks the pattern fromsearch(word, pos, node) onwards, starting atpos . At the end of the pattern it returnsnode , at a dot it tries every slot that is not empty, and at a letter it follows one slot.node.isWord
The main
public class DesignAddSearchWordsDataStructure {
private static class Node {
Node[] next = new Node[26]; // one slot per letter, 'a' to 'z'
boolean isWord; // true if a stored word ends here
}
private final Node root = new Node();
public void addWord(String word) {
Node cur = root;
for (char ch : word.toCharArray()) {
int i = ch - 'a';
if (cur.next[i] == null) {
cur.next[i] = new Node(); // no link for this letter yet
}
cur = cur.next[i];
}
cur.isWord = true;
}
public boolean search(String word) {
return search(word, 0, root);
}
private boolean search(String word, int pos, Node node) {
if (pos == word.length()) {
return node.isWord; // pattern used up: did a word end here?
}
char ch = word.charAt(pos);
if (ch == '.') {
for (Node child : node.next) { // '.' may be any letter: try every link
if (child != null && search(word, pos + 1, child)) {
return true;
}
}
return false;
}
Node child = node.next[ch - 'a'];
return child != null && search(word, pos + 1, child);
}
public static void main(String[] args) {
DesignAddSearchWordsDataStructure dict = new DesignAddSearchWordsDataStructure();
dict.addWord("bad");
dict.addWord("dad");
dict.addWord("mad");
String[] patterns = {"pad", "bad", ".ad", "b..", "ba", "...", "....", "b.b", ""};
for (String p : patterns) {
System.out.println("search(\"" + p + "\") = " + dict.search(p));
}
dict.addWord("ba");
System.out.println("after addWord(\"ba\"): search(\"ba\") = " + dict.search("ba")
+ ", search(\"..\") = " + dict.search(".."));
}
}
Running it prints:
search("pad") = false
search("bad") = true
search(".ad") = true
search("b..") = true
search("ba") = false
search("...") = true
search("....") = false
search("b.b") = false
search("") = false
after addWord("ba"): search("ba") = true, search("..") = true
The searches for padbad.adb..falsetruetruetruesearch("ba") = falsetrue..
Three dots match a stored word, while four dots give falseb.bfalse
What if the end of the pattern returned a plain truenode.isWordtrueba..
Complexity
Adding a word and searching with plain letters both depend only on the word's length; dots are what can make a search spread out.
- Time of addWord: O(L), because for each of the L letters of the word it reads or creates one slot and moves down one node.
- Time of search: O(L) without dots, because each plain letter allows only one link; with k dots it can grow to O(26k × L), since each dot may branch into 26 links that each walk the rest of the pattern.
- Space: O(T × 26), where T is the total number of letters added, because each letter can create one node with its 26 slots; a search adds up to L + 1 nested calls.
Allowing exactly one changed letter instead of a dot is