Skip to main content
37

Design Add and Search Words Data Structure

Mediumtriedesigndfs

Your code isn't saved yet: refreshing or leaving the page resets it. Saved progress comes with user accounts.

This problem uses:TriesRead the beginner guide

Design a word dictionary that supports searching with wildcards.

Implement the class WordDictionary:

  • new WordDictionary() creates an empty dictionary.
  • addWord(word) adds word.
  • search(word) returns true if some added word matches word.

Understand the problem

  • A wildcard is a character that stands for "anything". Here it's the dot ., and it matches exactly one letter, any letter.
  • A word matches the search string if they have the same length and every non-dot letter is equal in the same position.
  • ".ad" matches "bad", "dad" and "mad". "b.." matches any 3-letter word starting with b. But ".ad" does not match "ad" or "bead": lengths must be equal.

Example 1

text
ops:      ["WordDictionary", "addWord", "addWord", "addWord", "search", "search", "search", "search"]
args:     [[],               ["bad"],   ["dad"],   ["mad"],   ["pad"],  ["bad"],  [".ad"],  ["b.."]]
expected: [null,             null,      null,      null,      false,    true,     true,     true]
  • search("pad") → false: never added.
  • search("bad") → true: added.
  • search(".ad") → true: "bad" matches (so do "dad" and "mad").
  • search("b..") → true: "bad" matches.

How the tests work: each test is a sequence of calls. ops names each call (the first creates the object), args holds the arguments, and expected the return values.

Constraints

  • 1 <= word.length <= 25
  • Added words contain lowercase English letters; search strings may also contain ..
  • A search string has at most 2 dots.
  • At most 10^4 calls in total.

Hints

Stuck? Open one hint at a time. Each one gives away a little more than the last.

    The idea in one sentence

    Store the words in a trie; search walks it letter by letter, and at a dot it tries every child and succeeds if any of them leads to a match.

    The naive approach (and why it's slow)

    Keep the words in a list. For each search, compare it with every word: same length, and every non-dot letter equal. That's O(number of words × length) per search: with 10,000 words and many searches, it adds up.

    The key insight

    Use the trie from Implement Trie. addWord is the same as insert, and a search with no dots is the same walk as search.

    The only new thing is the dot. At a normal letter, there's exactly one child to follow. At a ., the letter could be anything, so the search branches: try every child, and if any branch matches, the answer is true.

    text
    match(node, i):          "can word[i..] be found below node?"
      i == word.length    →  node.isEnd        (used every character: did a word end here?)
      word[i] == '.'      →  true if ANY child c has match(c, i + 1)
      otherwise           →  follow the child for word[i]; false if it doesn't exist

    This is a depth-first search (DFS) that only spreads out at dots. Every real letter follows a single path, so most of the trie is never visited.

    Step by step

    After adding bad, dad, mad, the trie's root has three children: b, d, m, and each continues with a then d (an end).

    Search ".ad":

    PositionCharacterAt nodeWhat happens
    0.roottry each child: b first
    1abfollow a
    2db → afollow d
    3(end)b → a → disEnd is true → match!

    The first branch already matched, so we return true without trying d or m.

    The code

    The reference solution is below, with comments on every important line.

    How fast is it?

    With L = word length and d = number of dots:

    • addWord: O(L).
    • search: O(L) with no dots. Each dot can branch into up to 26 children, so the worst case is about O(26^d · L). With at most 2 dots, that's still small.
    • Memory: O(total letters added).

    Common mistakes

    • Returning true when the path exists but no word ends there. At the end, check isEnd.
    • Returning the result of the first child at a dot. If the first child fails, you must try the others. Return false only after all children fail.
    • Letting a dot match "zero letters" or several letters. It matches exactly one.

    Going deeper

    This is the trie's real superpower: a prefix-guided search that prunes everything not matching so far. The same idea, a DFS moving through a trie and another structure at the same time, is the heart of Word Search II.

    Reference solution

    js
    class TrieNode {
      children = new Map() // letter → next node
      isEnd = false // does a whole word end at this node?
    }
    
    export default class WordDictionary {
      root = new TrieNode()
    
      /**
       * @param {string} word
       * @return {void}
       */
      // Exactly Trie.insert: follow the letters, creating nodes as needed, then mark the end.
      addWord(word) {
        let node = this.root
        for (const char of word) {
          if (!node.children.has(char)) node.children.set(char, new TrieNode())
          node = node.children.get(char)
        }
        node.isEnd = true
      }
    
      /**
       * @param {string} word
       * @return {boolean}
       */
      search(word) {
        // Can word[i..] be found starting below this node?
        const match = (node, i) => {
          // Used every character: it's a match only if a word ends right here.
          if (i === word.length) return node.isEnd
          if (word[i] === '.') {
            // A dot can be ANY letter: try every child, succeed if any branch matches.
            for (const child of node.children.values()) {
              if (match(child, i + 1)) return true
            }
            return false
          }
          // A normal letter: there's only one way to go.
          const child = node.children.get(word[i])
          return child !== undefined && match(child, i + 1)
        }
        return match(this.root, 0)
      }
    }
    ts
    class TrieNode {
      children = new Map<string, TrieNode>() // letter → next node
      isEnd = false // does a whole word end at this node?
    }
    
    export default class WordDictionary {
      private root = new TrieNode()
    
      // Exactly Trie.insert: follow the letters, creating nodes as needed, then mark the end.
      addWord(word: string): void {
        let node = this.root
        for (const char of word) {
          let child = node.children.get(char)
          if (!child) {
            child = new TrieNode()
            node.children.set(char, child)
          }
          node = child
        }
        node.isEnd = true
      }
    
      search(word: string): boolean {
        // Can word[i..] be found starting below this node?
        const match = (node: TrieNode, i: number): boolean => {
          // Used every character: it's a match only if a word ends right here.
          if (i === word.length) return node.isEnd
          if (word[i] === '.') {
            // A dot can be ANY letter: try every child, succeed if any branch matches.
            for (const child of node.children.values()) {
              if (match(child, i + 1)) return true
            }
            return false
          }
          // A normal letter: there's only one way to go.
          const child = node.children.get(word[i])
          return child !== undefined && match(child, i + 1)
        }
        return match(this.root, 0)
      }
    }
    python
    class TrieNode:
        def __init__(self):
            self.children: dict[str, TrieNode] = {}  # letter → next node
            self.is_end = False  # does a whole word end at this node?
    
    
    class WordDictionary:
        def __init__(self):
            self.root = TrieNode()
    
        # Exactly Trie.insert: follow the letters, creating nodes as needed, then mark the end.
        def add_word(self, word: str) -> None:
            node = self.root
            for char in word:
                node = node.children.setdefault(char, TrieNode())
            node.is_end = True
    
        def search(self, word: str) -> bool:
            # Can word[i:] be found starting below this node?
            def match(node: TrieNode, i: int) -> bool:
                # Used every character: it's a match only if a word ends right here.
                if i == len(word):
                    return node.is_end
                if word[i] == ".":
                    # A dot can be ANY letter: try every child, succeed if any branch matches.
                    return any(match(child, i + 1) for child in node.children.values())
                # A normal letter: there's only one way to go.
                child = node.children.get(word[i])
                return child is not None and match(child, i + 1)
    
            return match(self.root, 0)