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) stores a word, and search(word) returns true if some stored word matches the pattern word. A pattern may contain dots, and each dot '.' matches any one letter. Words use the lowercase letters a to z.

Example
Input: addWord("bad"), addWord("dad"), addWord("mad"), then search("pad"), search("bad"), search(".ad"), search("b..")
Output: false, true, true, true
Solution

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, with a dot for the empty square, and you run through the words you know that fit. This problem asks for a word store that answers that kind of question.

Walk through the example. The store holds bad, dad and mad. Searching for pad gives false, because no stored word is pad, while bad gives true. In .ad the dot can be b, d or m, and each gives a stored word, so the answer is true. In b.., b followed by any two letters, bad fits.

The simple way is to keep the words in a list and compare the pattern with each one, letter by letter. For pad, that means checking bad, dad and mad, although the first letter alone rules out all three. With thousands of stored words, most of that work goes to words that never had a chance. Can the words be arranged so that a search only looks at words that still fit?

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.

The trie for bad, dad and mad: from the root, links b, d and m, each followed by a and then d, ending on a teal word end. The search for .ad lets the dot take the b link, then follows a and d to a word end and returns true. The d and m links are never tried.

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 .ad in the picture, using the pattern column on the left. The dot may be any letter, so at the root the search may take any link. It tries b first, since b comes before d and m in the alphabet, and that is the orange path. The next pattern letters, a and d, are plain letters, so each allows only the link with that letter. The path ends on a teal circle, so the search returns true. As the note at the top right says, d and m are never tried once b has matched.

A plain letter, on the other hand, rules out every other link at once. For pad the root has no p link, so the search stops before reading a single stored word. Put together, a plain letter follows one link, and a dot tries the links one after another until one of them leads to a word end.

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 object with an array of 26 slots, one per letter: slot 0 for a, slot 1 for b, up to slot 25 for z. The slot for a letter is the letter minus 'a', so b goes to slot 1.

A slot that is null means no stored word goes on with that letter. A boolean named isWord marks the teal circles. It is needed because a path does not always end a word: the circle reached by b and then a lies on the path of bad, but "ba" was never added.

Adding a word

How does addWord build a path? It starts at the root and takes the word one letter at a time. If the slot for the letter is empty, it puts a new node there, and then it moves down to that node. After the last letter it sets isWord on the node it stopped at. This is the same insert as in Implement Trie.

Searching with dots

What should search do at each letter of the pattern? A plain letter looks in its one slot, and if that slot is empty, this path cannot match. A dot tries every slot that is not empty, and the search succeeds if any of them leads to a match.

After a link is taken, what is left is the same question on a smaller scale. At the b link, the search for .ad from the root becomes a search for ad from the node under b. So the search method calls itself with the next position in the pattern and the node it moved to, which makes it recursive. If the b path had failed, the call would return false to the root, and the root would try d next.

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 isWord, not simply true. With bad, dad and mad stored, ba reaches the circle under b and a, which is not teal, so it does not match.

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:

  • Node: one circle of the trie, with next, the 26 link slots, and isWord, the word-end mark.
  • root: the node at the top, created with the object. Every word and every search starts there.
  • addWord: walks down from the root with cur, creates any missing node, and marks the last one with isWord.
  • search(word): the public method. It starts the helper at position 0 and the root.
  • search(word, pos, node): the helper. It checks the pattern from pos onwards, starting at node. At the end of the pattern it returns node.isWord, at a dot it tries every slot that is not empty, and at a letter it follows one slot.

The main method stores bad, dad and mad and runs the four searches from the example. Then it tries ba, the start of bad, then three and four dots, a pattern with no match and the empty pattern, and finally adds "ba" and searches again.

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

Output
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 pad, bad, .ad and b.. give false, true, true and true, the answers in the example. Next, search("ba") = false: the path b, a exists, but no word ends on it. Compare it with the last line, where the same search is true once "ba" has been added, and .. now finds it too.

Three dots match a stored word, while four dots give false, because after the third link there are no more. In b.b the dot takes the a link under b, and below it there is a d link but no b link. The empty pattern gives false as well, since the root is not a word end.

What if the end of the pattern returned a plain true instead of node.isWord? A copy of the class with that change, run on the same three words, answered true for ba, for .. and even for the empty pattern, though none of them was stored.

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 Implement Magic Dictionary.