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) stores a list of words. The method search(searchWord) returns true if changing exactly one letter of searchWord into a different letter gives one of the stored words, and false otherwise. All words are made of the lowercase letters a to z.

Example 1
Input: buildDict(["hello", "keyboard"]), then search("hello"), search("hhllo"), search("hell"), search("keyboards")
Output: false, true, false, false
Example 2
Input: buildDict(["hello", "hallo"]), then search("hello")
Output: true
Solution

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") is true.

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 find a stored word that is one letter away, without comparing against each stored word in turn? The answer is to store the words letter by letter, so that words with the same beginning share it. Look at the picture below.

The trie for hello and keyboard. From the root, one branch of links spells h, e, l, l, o and the other spells k, e, y, b, o, a, r, d, and the last circle of each is marked as a word end. The search word hhllo follows the hello branch in orange and spends its one change where the word has h and the link has e.

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 tracks its one change, and what must hold when the word runs out.

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 Node with an array next of 26 slots, one per letter. The link for a letter ch sits in next[ch - 'a'], so h goes in slot 7, and an empty slot (null) means there is no link with that letter. A flag isWord marks the ringed circles where a stored word ends.

To add a word, buildDict starts at the root and follows its letters one by one, creating a node wherever the slot is still empty. At the last letter it sets isWord.

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, telling it whether the path so far has spent the change.

Following the link with the word's own letter passes changed on as it is. Following any other link is allowed only while changed is false, and passes true from then on. If a call returns false, the call above it goes on to the next link out of its circle.

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 isWord set, and changed must be true. Without the second check, "hello" in Example 1 would match itself with no change at all. A stored word can still give true through a different stored word, as in Example 2, where "hello" becomes "hallo" by changing e to a.

Java Solution

The class has these parts:

  • Node: one circle of the trie, with next, its 26 links by letter, and isWord, set where a stored word ends.
  • root: the circle labelled root in the picture, where every word starts.
  • buildDict: adds each word, creating a node for each letter not yet in the trie.
  • search(searchWord): starts the walk at the root, at position 0, with the change unspent.
  • search(w, pos, node, changed): the recursive walk. It tries every link out of node; the link with the letter at pos keeps changed, and any other link spends it.

The main method runs both examples, one more search "keyboarc", and the dictionary "axx" and "bbc" with the search "abc".

Java
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:

Output
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, spends the change on the last letter, c to d. In the line starting "with hallo too", "hello" is true although it is stored, because "hallo" is one letter away.

The last line, search("abc") = true, is the retry at work: the path through a dies at "axx", and the loop at the root moves on to the link b. The check changed && node.isWord is what makes the first line false. With return node.isWord; instead, that line prints search("hello") = true, because "hello" reaches its own word end without spending the change.

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 Design Add and Search Words Data Structure.