Implement Magic Dictionary
Store a list of words, then tell whether a word is exactly one letter away from one of them.
Design a class with two methods. The method buildDict(dictionary)search(searchWord)searchWord
Example 1
Output: false, true, false, false
Example 2
Output: true
The Idea
Picture a word game: you must change one letter of a word into another letter, and the result must be in the dictionary. In Example 1 the dictionary holds "hello" and "keyboard". Changing the second letter of "hhllo" from h to e gives "hello", so search("hhllo")
The other three searches fail for different reasons. The word "hello" is already in the dictionary, so it needs zero changes, and the game asks for exactly one. Changing letters never alters a word's length, so "hell", with four letters, and "keyboards", with nine, cannot reach "hello" (five) or "keyboard" (eight).
So how does search
From the circle labelled root, a link labelled h starts the word "hello" and a link labelled k starts "keyboard". Each link adds one letter, so following links from the root spells a word. The teal ringed circles, labelled end of "hello" and end of "keyboard", mark where a stored word ends. This tree of letter links is called a trie. If "help" were added, it would reuse the links h, e and l and add one new link, p.
Now walk "hhllo" down the trie, along the orange path. Its first letter, h, matches the link h. Its second letter is h as well, but the only link out of that circle is e. That is where the one change is spent, as the label at the top says: h is not e. From then on every letter must match, and l, l and o lead to the circle labelled end of "hello".
Sometimes the change could go in more than one place, and the first try can fail. So at every circle there are two kinds of moves: follow the link with the word's own letter and keep the change, or follow any other link and spend the change, if it is still unspent. The answer is true when some path reaches a word end with the change spent.
Solution Approach
Turning that idea into code means settling four things: the cost of the simple way without a trie, how the trie is stored, how search
Comparing with every stored word
What is the simplest way? Keep the words in a list. For each stored word of the same length as the search word, count the positions where the letters differ, and return true if some word differs in exactly one. That works, but every search reads every stored word of that length, even when hundreds of them share their first letters. In the trie, a shared beginning such as "he" in "hello" and "help" is read once for all of them.
Storing the trie
How does a circle in the picture become Java? Each circle is a Nodenextchnext[ch - 'a']nullisWord
To add a word, buildDictisWord
Keeping track of the one change
How does the walk remember whether the change is spent? The search method handles one letter at one circle and then calls itself for the next letter at the next circle. For "hhllo", the call for the second h sits at the circle after the link h. Handing the rest of "hhllo" to another call of the same method is what makes the walk recursive. Each call also receives a flag, changed
Following the link with the word's own letter passes changedchanged
That retry matters. Take a dictionary with "axx" and "bbc", and search "abc". Keeping the a leads to a circle whose only link is x, so the change turns b into x, and then c does not match the next x. The walk fails there, returns to the root, and spends the change on the first letter instead: a becomes b, and "bbc" is found.
When the search word runs out
What must hold once every letter is used? Two things: the node reached must have isWordchanged
Java Solution
The class has these parts:
: one circle of the trie, withNode , its 26 links by letter, andnext , set where a stored word ends.isWord : the circle labelled root in the picture, where every word starts.root : adds each word, creating a node for each letter not yet in the trie.buildDict : starts the walk at the root, at position 0, with the change unspent.search(searchWord) : the recursive walk. It tries every link out ofsearch(w, pos, node, changed) ; the link with the letter atnode keepspos , and any other link spends it.changed
The main
public class ImplementMagicDictionary {
private static class Node {
Node[] next = new Node[26]; // one slot per letter, a to z
boolean isWord; // a dictionary word ends here
}
private final Node root = new Node();
public void buildDict(String[] dictionary) {
for (String word : dictionary) {
Node cur = root;
for (char ch : word.toCharArray()) {
int i = ch - 'a';
if (cur.next[i] == null) cur.next[i] = new Node();
cur = cur.next[i];
}
cur.isWord = true;
}
}
// True if changing exactly one letter of searchWord gives a dictionary word.
public boolean search(String searchWord) {
return search(searchWord, 0, root, false);
}
private boolean search(String w, int pos, Node node, boolean changed) {
if (pos == w.length()) return changed && node.isWord; // exactly one change, no fewer
int want = w.charAt(pos) - 'a';
for (int i = 0; i < 26; i++) {
Node child = node.next[i];
if (child == null) continue;
if (i == want) {
if (search(w, pos + 1, child, changed)) return true; // keep the letter
} else if (!changed) {
if (search(w, pos + 1, child, true)) return true; // spend the one change
}
}
return false;
}
public static void main(String[] args) {
ImplementMagicDictionary dict = new ImplementMagicDictionary();
dict.buildDict(new String[] {"hello", "keyboard"});
for (String w : new String[] {"hello", "hhllo", "hell", "keyboards", "keyboarc"}) {
System.out.println("search(\"" + w + "\") = " + dict.search(w));
}
ImplementMagicDictionary two = new ImplementMagicDictionary();
two.buildDict(new String[] {"hello", "hallo"});
System.out.println("with hallo too: search(\"hello\") = " + two.search("hello"));
ImplementMagicDictionary detour = new ImplementMagicDictionary();
detour.buildDict(new String[] {"axx", "bbc"});
System.out.println("axx and bbc: search(\"abc\") = " + detour.search("abc"));
}
}
Running it prints:
search("hello") = false
search("hhllo") = true
search("hell") = false
search("keyboards") = false
search("keyboarc") = true
with hallo too: search("hello") = true
axx and bbc: search("abc") = true
The first four lines answer Example 1: of "hello", "hhllo", "hell" and "keyboards", only "hhllo" gives true. The fifth line, search("keyboarc") = true
The last line, search("abc") = truechanged && node.isWordreturn node.isWord;search("hello") = true
Complexity
Building touches each stored letter once, and a search costs most when the change can be spent in many places.
- Time for buildDict: O(total letters), because each letter of each stored word moves one step down the trie and creates at most one node.
- Time for search: O(L2) for a search word of L letters, because the change can be spent at any of L positions on up to 25 other links, and each such path then follows at most L letters.
- Space: O(26 × total letters), because each stored letter can add one node with 26 slots, and a search adds at most L + 1 calls on the stack.
When the search word may contain dots that match any letter, see