> ## Documentation Index
> Fetch the complete documentation index at: https://leetcode-py.wisl.dev/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> leetcode-py is a Python LeetCode practice environment generator with one CLI: lcpy. It is not a service or platform.
> Each problem is a directory under leetcode/ with README.md, solution.py, test_solution.py, helpers.py, and playground.ipynb. lcpy gen creates them from JSON templates bundled with the package.
> Examples are backed by tests; copy them verbatim.

# Design Add and Search Words Data Structure

> Tested Python solution for LeetCode 211 with 13 pytest cases. Generate a practice environment with lcpy.

LeetCode 211, Medium. Topics: String, Depth-First Search, Design, Trie. [View on LeetCode](https://leetcode.com/problems/design-add-and-search-words-data-structure/description/).

Generate this problem as a practice environment: tested reference solution, 13 [parametrized pytest cases](/practice/testing), and a playground notebook:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
lcpy gen -n 211   # by problem number
lcpy gen -s design_add_and_search_words_data_structure   # by problem name
```

## 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.

### Examples

```
Input
["WordDictionary","addWord","addWord","addWord","search","search","search","search"]
[[],["bad"],["dad"],["mad"],["pad"],["bad"],[".ad"],["b.."]]
Output
[null,null,null,null,false,true,true,true]

Explanation
WordDictionary wordDictionary = new WordDictionary();
wordDictionary.addWord("bad");
wordDictionary.addWord("dad");
wordDictionary.addWord("mad");
wordDictionary.search("pad"); // return False
wordDictionary.search("bad"); // return True
wordDictionary.search(".ad"); // return True
wordDictionary.search("b.."); // return True
```

### Constraints

* `1 <= word.length <= 25`
* `word` in `addWord` consists of lowercase English letters.
* `word` in `search` consist of `'.'` or lowercase English letters.
* There will be at most `2` dots in `word` for `search` queries.
* At most `10^4` calls will be made to `addWord` and `search`.

## Solution

Reference implementation from [solution.py on GitHub](https://github.com/wislertt/leetcode-py/blob/main/leetcode/design_add_and_search_words_data_structure/solution.py), full suite in [test\_solution.py](https://github.com/wislertt/leetcode-py/blob/main/leetcode/design_add_and_search_words_data_structure/test_solution.py):

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
from typing import Any


class WordDictionary:
    # Time: O(1)
    # Space: O(1)
    def __init__(self) -> None:
        self.root: dict[str, Any] = {}

    # Time: O(m) where m = len(word)
    # Space: O(m) for new word
    def add_word(self, word: str) -> None:
        node = self.root
        for char in word:
            if char not in node:
                node[char] = {}
            node = node[char]
        node["#"] = True

    # Time: O(n * 26^k) where n = len(word), k = number of dots
    # Space: O(n) for recursion stack
    def search(self, word: str) -> bool:
        def dfs(i: int, node: dict[str, Any]) -> bool:
            if i == len(word):
                return "#" in node

            char = word[i]
            if char == ".":
                return any(key != "#" and dfs(i + 1, node[key]) for key in node)
            else:
                return char in node and dfs(i + 1, node[char])

        return dfs(0, self.root)
```

## Complexity

| Time | Space |
| ---- | ----- |
| O(1) | O(1)  |

## Tags

[Grind](/catalog/grind), [Blind 75](/catalog/blind-75), [NeetCode 150](/catalog/neetcode-150), [NeetCode 250](/catalog/neetcode-250), [NeetCode All](/catalog/neetcode).
