</>

211. Design Add and Search Words Data Structure

Medium NeetCode 150
Tries Time O(m) Space O(m)
↗ Open on LeetCode Source: NeetCode 150

Quick review

Pattern
Tries
Time
O(m)
Space
O(m)

Standard Solution (C++)

SummaryDesign a data structure that supports inserting words into a dictionary and searching for words where the query may contain '.' wildcards, each of which can match any single letter.

Approach
  • Use a Trie (prefix tree) where each node holds 26 child pointers (one per lowercase letter) and an isEnd flag.
  • addWord walks/creates nodes character by character in O(m) time.
  • search uses recursive DFS: for a literal character, step into the matching child; for '.', branch into all non-null children and return true if any branch succeeds.
  • Worst-case search on an all-dot query explores every path, but in practice the branching is tightly bounded by the words actually stored.

#include <string>
#include <array>
using namespace std;

// Trie node: 26 children (a–z) + end-of-word marker
struct TrieNode {
    array<TrieNode*, 26> ch{};
    bool isEnd = false;
    ~TrieNode() { for (auto* c : ch) delete c; }
};

class WordDictionary {
public:
    WordDictionary() : root(new TrieNode()) {}
    ~WordDictionary() { delete root; }

    // Insert word into the trie, one character at a time.
    void addWord(string word) {
        TrieNode* cur = root;
        for (char c : word) {
            int idx = c - 'a';
            if (!cur->ch[idx])
                cur->ch[idx] = new TrieNode();
            cur = cur->ch[idx];
        }
        cur->isEnd = true;
    }

    // Return true if word (possibly containing '.') exists in the dictionary.
    bool search(string word) {
        return dfs(root, word, 0);
    }

private:
    TrieNode* root;

    // DFS through the trie matching word[pos..] from node cur.
    bool dfs(TrieNode* cur, const string& word, int pos) {
        if (pos == (int)word.size())
            return cur->isEnd;

        char c = word[pos];
        if (c == '.') {
            // Wildcard: try every existing child.
            for (TrieNode* child : cur->ch)
                if (child && dfs(child, word, pos + 1))
                    return true;
            return false;
        }

        // Literal character: follow exactly one child.
        TrieNode* child = cur->ch[c - 'a'];
        return child && dfs(child, word, pos + 1);
    }
};

/**
 * WordDictionary* obj = new WordDictionary();
 * obj->addWord(word);
 * bool found = obj->search(word);
 */
Time O(m) for addWord; O(26^m) worst-case for search on an all-'.' query of length m, O(m) for a fully literal query Space O(N·m) total trie storage for N words of average length m; O(m) recursion stack depth per search

A canonical reference solution. Problem statement © LeetCode — see the official link above.

My Solution (C++)

#include <string>
using namespace std;

class TrieNode {
public:    
    TrieNode* children[26];
    bool isEnd;

    TrieNode(){
        for(auto& c: children){
            c=nullptr;
        }
        isEnd=false;
    }
};
class WordDictionary {
public:
    WordDictionary() {
        root=new TrieNode();
    }
    ~WordDictionary(){
        clear(root);
    }
    
    void addWord(string word) {
        TrieNode* cur=root;
        for(const char &c: word){
            int i=c-'a';
            if(!cur->children[i]){
                cur->children[i]=new TrieNode();
            }
            cur=cur->children[i];
        }
        cur->isEnd=true;
    }
    
    bool search(string word) {
       return dfs(root, word, 0);
    }

private:
    TrieNode* root;

    bool dfs(TrieNode* cur, const string& word, int idx){
        if(idx==word.size()){
            return cur->isEnd;
        }
        char c=word[idx];
        if(c=='.'){
            for(int i=0; i<26; ++i){
                if(cur->children[i] && dfs(cur->children[i], word, idx+1)){
                    return true;
                }
            }
            return false;
        }
        int i=c-'a';
        if(!cur->children[i]){
            return false;
        }
        return dfs(cur->children[i], word, idx+1);
    }

    void clear(TrieNode* node){
        if(!node){
            return;
        }
        for(auto c: node->children){
            if(c){
                clear(c);
            }
        }
        delete node;
    }
};

/**
 * Your WordDictionary object will be instantiated and called as such:
 * WordDictionary* obj = new WordDictionary();
 * obj->addWord(word);
 * bool param_2 = obj->search(word);
 */

// Time Complexity: O(m) for addWord and search, where m is the length of the input word. In the worst case, search can take O(26^m) time if the word consists of '.' characters and matches all possible combinations of letters.
// Space Complexity: O(m) for addWord, since we may need to create up to m new TrieNodes in the worst case. The space complexity for search is O(m) due to the recursion stack in the worst case when the word consists of '.' characters.
Time O(m) Space O(m)

My own solution and notes, as I wrote them.

▶ Run it — editable in-browser playground C++

Your solution. A driver couldn't be auto-generated for this signature — add a main() that calls the method and prints the result, then Run.

C++ ▶ Runnable Couldn't auto-generate a driver for this signature — edit to add one.

Runs in a free public sandbox (Wandbox). Output and timing include network latency; don't paste secrets.

Related — same pattern