# 211. Design Add and Search Words Data Structure

{% embed url="<https://leetcode.com/problems/design-add-and-search-words-data-structure/description/>" %}

```jsx
function Trie(c, done = false) {
    this.dict = {};
}

var WordDictionary = function () {
    this.dict = {};
};

/** 
 * @param {string} word
 * @return {void}
 */
WordDictionary.prototype.addWord = function (word) {
    let currentDict = this.dict;
    for (let i = 0; i < word.length; i++) {
        const c = word[i];
        currentDict[c] = currentDict[c] ?? {};
        currentDict = currentDict[c];
    }
    currentDict.done = true;
    return null;
};

/** 
 * @param {string} word
 * @return {boolean}
 */
WordDictionary.prototype.search = function (word, idx = 0, dict = this.dict) {
    if (idx === word.length) {
        return !!dict.done;
    }

    const c = word[idx];

    if (c === '.') {
        for (const [key, value] of Object.entries(dict)) {
            const isValid = this.search(word, idx + 1, dict[key]);
            if (isValid) return true;
        }
    } else {
        if (dict[c] === undefined) return false;
        return this.search(word, idx + 1, dict[c]);
    }

    return false;
};

/** 
 * Your WordDictionary object will be instantiated and called as such:
 * var obj = new WordDictionary()
 * obj.addWord(word)
 * var param_2 = obj.search(word)
 */
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://algorithm.prettylog.com/top-75-leetcode-questions-to-save-your-time/problems/tree/211.-design-add-and-search-words-data-structure.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
