Start learning free

LESSON 503 OF 671 · TRIES

Design Add and Search Words in Java: Trie with Dot Wildcards

Practice O(L) Read the full explanation

Design a data structure that stores words and finds them again, where the word you search for may contain dots: a dot '.' matches any one letter.

Implement the class WordDictionary:

  • WordDictionary() creates an empty dictionary of words.
  • addWord(word) adds word to it.
  • search(word) returns true if some added word matches word, and false otherwise. An added word matches when it has the same length and, at every position, the same letter as word; where word has a dot, any letter matches.

The input is a list of operations, applied in order to one new dictionary. The output lists what the search calls return, in order. The starter code spells these names the way your language does.

 

Example 1:

Input:
    addWord("bad")
    addWord("dad")
    addWord("mad")
    search("pad")
    search("bad")
    search(".ad")
    search("b..")
Output: false true true true
Explanation: "pad" was never added. ".ad" matches "bad", "dad" and "mad", and "b.." matches "bad".

Example 2:

Input:
    addWord("a")
    addWord("ab")
    search(".")
    search("a.")
    search(".b")
    search(".a")
    search("..")
    search("b")
Output: true true true false true false
Explanation: "." matches the one-letter word "a", and "a.", ".b" and ".." all match "ab". No added word has "a" as its second letter, and "b" was never added.

Example 3:

Input:
    addWord("at")
    search("a")
    search("at.")
    search(".t")
    search("a..")
    search(".")
Output: false false true false false
Explanation: A dot stands for exactly one letter, never for none, so "at." and "a.." need a three-letter word and "." a one-letter word. "a" is the beginning of "at", but a search must match a whole word.

 

Constraints:

  • 1 <= word.length <= 25
  • A word passed to addWord consists of lowercase English letters, a to z.
  • A word passed to search consists of lowercase English letters and dots, with at most 2 dots.
  • At most 105 calls in total are made to addWord and search.

Note:

addWord should run in O(L) time, where L is the length of the word. A search without dots takes O(L) time too; at a dot it may have to try every child of the node it has reached.

STEP 1 OF 17
    Ctrl + Enter to check

    JAVA · TRIES

    Design Add And Search Words Data Structure in Java, explained

    Problem overview

    The class WordDictionary stores words and finds them again. addWord(String word) adds a word made of lowercase letters. search(String word) returns true if some added word matches the query. A match needs the same length, and at every position either the same letter or a dot in the query, because a dot '.' matches any single letter. A dot never matches "no letter".

    After adding "bad", "dad" and "mad": search("pad") is false, search("bad") is true, search(".ad") is true and search("b..") is true. After adding only "at", search("a") is false because a search must match a whole word, search("at.") is false because the dot needs a third letter, and search(".t") is true.

    A search with no dots should take O(L) time, like addWord. At a dot, it may have to try every child of the node it has reached.

    Approach: a trie, and a recursive search that branches at dots

    The words go into a trie: one node per prefix, each with a map from the next letter to a child node, and a flag isEnd on the node where an added word finishes. Adding a word walks down from the root, creating the missing nodes, and sets the flag on the last one.

    Searching a plain word follows one path, because each letter leads to at most one child. A dot breaks this: it can be any letter, so the search can't know which child to take. It has to try them all, and one successful branch is enough.

    That is a natural fit for recursion. The helper searchFrom(node, word, i) answers one question: does the rest of word, from index i on, match some path that starts at node? A letter makes one recursive call, and a dot makes one call per child. The search has at most two dots, so the number of branches stays small.

    Step by step

    1. Build the node class. TrieNode gets children, a Map<Character, TrieNode> set to a new HashMap, and a boolean isEnd that starts as false. The initial values mean that no constructor is needed.
    2. Give WordDictionary a root, a new TrieNode. It stands for the empty prefix.
    3. Write addWord. Start node at root. For each letter of word.toCharArray(), if node.children has no key for it, put a new node there; then move down with node = node.children.get(c). After the loop set node.isEnd = true. The flag is what makes a word count as added instead of only being the start of a longer word.
    4. Write search as a single line that returns searchFrom(root, word, 0).
    5. Base case of searchFrom. If i == word.length(), every character has been matched, so return node.isEnd. Being on the right path isn't enough: some added word must end exactly here.
    6. Read the current character into char c = word.charAt(i).
    7. Handle a dot. If c == '.', loop over node.children.values(), the child nodes. For each child, if searchFrom(child, word, i + 1) is true, return true at once. After the loop, return false: no child led to a match.
    8. Handle a letter. If node.children has no key c, return false. Otherwise return searchFrom(node.children.get(c), word, i + 1). There is no loop here, since a letter has only one way to go.

    The solution in Java

    class TrieNode {
        Map<Character, TrieNode> children = new HashMap<>();
        boolean isEnd = false;
    }
    
    class WordDictionary {
        TrieNode root = new TrieNode();
    
        public void addWord(String word) {
            TrieNode node = root;
            for (char c : word.toCharArray()) {
                if (!node.children.containsKey(c)) {
                    node.children.put(c, new TrieNode());
                }
                node = node.children.get(c);
            }
            node.isEnd = true;
        }
    
        public boolean search(String word) {
            return searchFrom(root, word, 0);
        }
    
        boolean searchFrom(TrieNode node, String word, int i) {
            if (i == word.length()) {
                return node.isEnd;
            }
            char c = word.charAt(i);
            if (c == '.') {
                for (TrieNode child : node.children.values()) {
                    if (searchFrom(child, word, i + 1)) {
                        return true;
                    }
                }
                return false;
            }
            if (!node.children.containsKey(c)) {
                return false;
            }
            return searchFrom(node.children.get(c), word, i + 1);
        }
    }
    

    Java details worth understanding:

    • Character literals use single quotes. '.' is a char; "." would be a String. Comparing c == '.' compares two char values, which is correct with ==.
    • Map keys are Character objects. The char c is boxed automatically for containsKey, put and get.
    • values() gives the map's values, here the child nodes, so the dot branch loops over them without needing the letters. A HashMap gives no promise about the order, which doesn't matter because every child is tried.
    • Imports. Map and HashMap live in java.util, so a file of your own needs import java.util.*;.
    • The helper has no public. It is an internal detail, called only from search.

    Complexity

    addWord: O(L) time for a word of length L, with one map operation per letter.

    search without dots: O(L). Each level makes one recursive call.

    search with dots: at a dot, the search branches into every child, up to 26 for lowercase letters. With at most two dots, that is at most 26 * 26 branches, each continuing for at most L levels, which is a constant factor on top of O(L). Without a limit on dots it could visit much of the trie.

    Space: the trie holds at most one node per letter of the added words. The recursion adds O(L) stack frames.

    Edge cases and common mistakes

    • A prefix isn't a match. With only "at" added, search("a") is false. The base case returns node.isEnd, not true.
    • A dot needs exactly one letter. search("at.") and search("a..") are false when only "at" is added, and search(".") is false too.
    • A dot can match a letter that ends a word. With "a" and "ab" added, search(".") is true because the node for "a" has isEnd set, while search(".a") is false, since no added word has "a" as its second letter.
    • Returning after the first child at a dot. The search must try every child until one succeeds. Returning the result of only the first child would miss matches in the others.
    • Forgetting isEnd. Without it, "ba" would match after adding only "bad".

    Testing

    These results come from running the class:

    • Add "bad", "dad", "mad", then search "pad", "bad", ".ad", "b..": false, true, true, true.
    • Add "a", "ab", then search ".", "a.", ".b", ".a", "..", "b": true, true, true, false, true, false.
    • Add "at", then search "a", "at.", ".t", "a..", ".": false, false, true, false, false.
    • Add "at", "an", then search "a.", "..": true, true.
    Keep going with Java650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free