Skip to content
Veltoryx Technologies
FreeProblem 150● Mediumleetcode ↗4 min readUpdated 30 October 2026

Design Add and Search Words Data Structure

Implement a prefix tree that supports wildcard search with '.' using recursive depth-first search backtracking.

01The problem

Design a data structure that supports adding new words and finding if a string matches any previously added string.

Implement the WordDictionary class:

  • WordDictionary() Initializes the object.
  • void addWord(word) Adds word to the data structure, it can be matched later.
  • bool search(word) Returns true if there is any string in the data structure that matches word or false otherwise. word may contain dots '.' where dots can be matched with any letter.

02How to spot it

  • Words are added dynamically and searched with literal characters and wildcard '.' characters.
  • A regular character matches exactly one child node: follow node.next[ch - 'a'].
  • A wildcard '.' can match any letter from 'a' to 'z': branch across all existing children using depth-first search (DFS).
  • Combines Trie prefix tree storage with recursive backtracking.

03Pseudocode

text
match(w, i, node):
  if i == len(w): return node.isWord
  if w[i] != '.':
    child = node.next[w[i]]
    return child and match(w, i+1, child)
  for each child of node:
    if match(w, i+1, child): return true
  return false

04Watch it work

Visualizer · step through the algorithmops = [["addWord","bad"],["addWord","dad"],["addWord","mad"],["search","pad"],["search","bad"],["search",".ad"],["search","b.."]]

dictionary

initialized

Initialize WordDictionary Trie root. '.' wildcards match any child letter during DFS.

Pseudocode

  1. match(w, i, node):
  2. if i == len(w): return node.isWord
  3. if w[i] != '.':
  4. child = node.next[w[i]]
  5. return child and match(w, i+1, child)
  6. for each child of node:
  7. if match(w, i+1, child): return true
  8. return false

Variables

storedWords
step 1 / 8

05Step-by-step dry run

  1. addWord("bad"), addWord("dad"), addWord("mad"):
    • Root has children for 'b', 'd', 'm'. Each child leads to 'a' -> 'd' with isWord = true.
  2. search("pad"):
    • Root has no child for 'p' -> returns false.
  3. search("bad"):
    • Direct match: 'b' -> 'a' -> 'd' exists and isWord == true -> returns true.
  4. search(".ad"):
    • First character is '.': try all children of root ('b', 'd', 'm').
    • Try child 'b': recursively search "ad" starting from node 'b'.
    • Node 'b' has child 'a', which has child 'd' with isWord == true -> matches!
    • Returns true immediately without needing to search 'd' or 'm'.
  5. search("b.."):
    • First character 'b': follow child 'b'.
    • Second character '.': try child 'a'.
    • Third character '.': try child 'd'. Node 'd' has isWord == true -> returns true.

06Java solution

java
public class Main {
    static class WordDictionary {
        private final WordDictionary[] next = new WordDictionary[26];
        private boolean isWord;

        public WordDictionary() {}

        public void addWord(String word) {
            WordDictionary node = this;
            for (char ch : word.toCharArray()) {
                int i = ch - 'a';
                if (node.next[i] == null) {
                    node.next[i] = new WordDictionary();
                }
                node = node.next[i];
            }
            node.isWord = true;
        }

        public boolean search(String word) {
            return match(word, 0, this);
        }

        private boolean match(String w, int i, WordDictionary node) {
            if (i == w.length()) return node.isWord;
            char ch = w.charAt(i);

            if (ch != '.') {
                WordDictionary child = node.next[ch - 'a'];
                return child != null && match(w, i + 1, child);
            }

            for (WordDictionary child : node.next) {
                if (child != null && match(w, i + 1, child)) {
                    return true;
                }
            }
            return false;
        }
    }

    public static void main(String[] args) {
        WordDictionary dict = new WordDictionary();
        dict.addWord("bad");
        dict.addWord("dad");
        dict.addWord("mad");
        System.out.println(dict.search("pad"));
        System.out.println(dict.search("bad"));
        System.out.println(dict.search(".ad"));
        System.out.println(dict.search("b.."));
    }
}
Expected output
false
true
true
true

07Why it works

Without wildcards, searching follows the single deterministic path dictated by the characters. When a dot '.' is encountered, it can match any character, so the algorithm branches across all non-null children. If any branch successfully completes the match (match(...) == true), the function short-circuits and returns true. If all children branches fail, it returns false.

08Time and space

  • Time complexity:
    • addWord(word): O(L) where L is word length.
    • search(word): O(L) for queries without dots; O(26^d · L) in the worst case where d is the number of dots in the pattern. With at most 2 dots, 26^2 = 676 branches, making search fast.
  • Space complexity: O(totalCharacters · 26) for the trie structure, plus O(L) recursion stack during search.

09Edge cases

  • Search with all dots "...": Explores words of length 3; returns true if any 3-letter word exists.
  • Dot at the end of word: Must verify that the terminal node has isWord == true.
  • Pattern longer than any stored word: Reaches null child; returns false.

10Common mistakes

  • Returning true on end of pattern without checking isWord: Pattern ".." matching prefix "ba" of "bad" would falsely return true if isWord is not checked.
  • Only searching the first child when encountering '.' : A dot must branch across all existing children until a match is found.

11Other approaches

  • Group words by length: Maintain a map of word length to list of words, using regex or character comparison. Slower for large dictionaries, but prunes searches on mismatched word lengths.

12In the interview

  1. Point out the composition: Trie for prefix indexing plus DFS backtracking for wildcard branches.
  2. Highlight early exit: as soon as any child branch returns true, return true immediately without exploring remaining branches.
  3. Note constraints: with at most 2 dots per search, exponential branch explosion is strictly bounded (26^2 = 676).

13Quiz

What is the worst-case number of branches explored when searching a pattern with d dots?

  • (Recommended) O(26^d)
  • O(d^26)
  • O(26 · d)
  • O(d!)

Answer: O(26^d). Each dot can branch into up to 26 possible children, multiplying the search tree by 26 for each wildcard level.

14Solve it yourself

Open LeetCode #211 and submit the Trie + DFS solution.