211. Design Add and Search Words Data Structure LeetCode Solution

In this guide, you will get 211. Design Add and Search Words Data Structure LeetCode Solution with the best time and space complexity. The solution to Design Add and Search Words Data Structure problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.

Table of Contents

  1. Problem Statement
  2. Complexity Analysis
  3. Design Add and Search Words Data Structure solution in C++
  4. Design Add and Search Words Data Structure solution in Java
  5. Design Add and Search Words Data Structure solution in Python
  6. Additional Resources
211. Design Add and Search Words Data Structure LeetCode Solution image

Problem Statement of Design Add and Search Words Data Structure

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.

Example:

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 104 calls will be made to addWord and search.

Example not found

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 104 calls will be made to addWord and search.

Complexity Analysis

  • Time Complexity:
  • Space Complexity:

211. Design Add and Search Words Data Structure LeetCode Solution in C++

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;
  }
};
/* code provided by PROGIEZ */

211. Design Add and Search Words Data Structure LeetCode Solution in Java

class TrieNode {
  public TrieNode[] children = new TrieNode[26];
  public boolean isWord = false;
}

class WordDictionary {
  public void addWord(String word) {
    TrieNode node = root;
    for (final char c : word.toCharArray()) {
      final int i = c - 'a';
      if (node.children[i] == null)
        node.children[i] = new TrieNode();
      node = node.children[i];
    }
    node.isWord = true;
  }

  public boolean search(String word) {
    return dfs(word, 0, root);
  }

  private TrieNode root = new TrieNode();

  private boolean dfs(String word, int s, TrieNode node) {
    if (s == word.length())
      return node.isWord;
    if (word.charAt(s) != '.') {
      TrieNode next = node.children[word.charAt(s) - 'a'];
      return next == null ? false : dfs(word, s + 1, next);
    }

    // If word[s] == '.', then search all the 26 children.
    for (int i = 0; i < 26; ++i)
      if (node.children[i] != null && dfs(word, s + 1, node.children[i]))
        return true;

    return false;
  }
}
// code provided by PROGIEZ

211. Design Add and Search Words Data Structure LeetCode Solution in Python

class TrieNode:
  def __init__(self):
    self.children: dict[str, TrieNode] = {}
    self.isWord = False


class WordDictionary:
  def __init__(self):
    self.root = TrieNode()

  def addWord(self, word: str) -> None:
    node: TrieNode = self.root
    for c in word:
      node = node.children.setdefault(c, TrieNode())
    node.isWord = True

  def search(self, word: str) -> bool:
    return self._dfs(word, 0, self.root)

  def _dfs(self, word: str, s: int, node: TrieNode) -> bool:
    if s == len(word):
      return node.isWord
    if word[s] != '.':
      child: TrieNode = node.children.get(word[s], None)
      return self._dfs(word, s + 1, child) if child else False
    return any(self._dfs(word, s + 1, child) for child in node.children.values())
# code by PROGIEZ

Additional Resources

Happy Coding! Keep following PROGIEZ for more updates and solutions.