Problem solution · C++

Add and Search Word - Data structure design

Add and Search Word - Data structure design: a C++ solution using depth-first search. Learn the idea, check the complexity, and read the full code, with credit to walkccc LeetCode Solutions.

Technique
Depth-first search
Source
walkccc LeetCode Solutions
Length
43 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

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.

  1. Define the state carried into one recursive or stack frame.
  2. Mark or choose the current state before exploring children.
  3. 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.

Source

Code and credit

This code comes from walkccc LeetCode Solutions by P.-Y. Chen (walkccc) and is used under the MIT licence.

Full codeAdd and Search Word - Data structure design · C++C++
Use this to learn the idea, then write your own version.
struct TrieNode {  vector<shared_ptr<TrieNode>> children;  bool isWord = false;  TrieNode() : children(26) {}}; class WordDictionary { public:  void addWord(const string& word) {    shared_ptr<TrieNode> node = root;    for (const char c : word) {      const int i = c - 'a';      if (node->children[i] == nullptr)        node->children[i] = make_shared<TrieNode>();      node = node->children[i];    }    node->isWord = true;  }   bool search(const string& word) {    return dfs(word, 0, root);  }  private:  shared_ptr<TrieNode> root = make_shared<TrieNode>();   bool dfs(const string& word, int s, shared_ptr<TrieNode> node) {    if (s == word.length())      return node->isWord;    if (word[s] != '.') {      shared_ptr<TrieNode> next = node->children[word[s] - 'a'];      return next ? dfs(word, s + 1, next) : false;    }     // If word[s] == '.', then search all the 26 children.    for (int i = 0; i < 26; ++i)      if (node->children[i] && dfs(word, s + 1, node->children[i]))        return true;     return false;  }}; 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗