Approach
Depth-first search
For Add and Search Word - Data structure design, the implementation follows one branch at a time, making it suitable for components, trees, backtracking, or dependency exploration.
- Define the state carried into one recursive or stack frame.
- Mark or choose the current state before exploring children.
- Combine child results or undo the choice when the branch finishes.
Code notes
- 43 lines of C++ from the credited upstream file 211.cpp.
- The implementation visibly relies on sequence storage.
- 2 loop blocks detected, together with recursive traversal.
Complexity
Count unique states for graph traversal; for backtracking, count the branching factor and maximum depth.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1struct TrieNode {2 vector<shared_ptr<TrieNode>> children;3 bool isWord = false;4 TrieNode() : children(26) {}5};6 7class WordDictionary {8 public:9 void addWord(const string& word) {10 shared_ptr<TrieNode> node = root;11 for (const char c : word) {12 const int i = c - 'a';13 if (node->children[i] == nullptr)14 node->children[i] = make_shared<TrieNode>();15 node = node->children[i];16 }17 node->isWord = true;18 }19 20 bool search(const string& word) {21 return dfs(word, 0, root);22 }23 24 private:25 shared_ptr<TrieNode> root = make_shared<TrieNode>();26 27 bool dfs(const string& word, int s, shared_ptr<TrieNode> node) {28 if (s == word.length())29 return node->isWord;30 if (word[s] != '.') {31 shared_ptr<TrieNode> next = node->children[word[s] - 'a'];32 return next ? dfs(word, s + 1, next) : false;33 }34 35 36 for (int i = 0; i < 26; ++i)37 if (node->children[i] && dfs(word, s + 1, node->children[i]))38 return true;39 40 return false;41 }42};43