Design Add and Search Words Data Structure in Python and Java
In this tutorial, we will learn LeetCode #211: Design Add and Search Words Data Structure in very simple language. We will understand the idea step by step, see custom examples, and write complete code in Python and Java.
What Is the Design Add and Search Words Data Structure Problem?
This problem asks us to solve a common coding interview task using the given input. The goal is to return the correct result without using a slow brute force method.
For this problem, we will use trie with dfs because it gives a clean and optimized solution.
Example input:
operations = addWord("bad"), addWord("dad"), search(".ad")
Expected result:
Output: true
Explanation:
Dot can match b or d.Beginner-Friendly Idea
The main idea is to avoid trying every possible answer blindly. Instead, we keep useful information while reading the input and use that information to make the next decision.
At each step, ask: “What do I already know, and how does the current value change my answer?”
Using our example:
operations = addWord("bad"), addWord("dad"), search(".ad")
Approach:
trie with dfs
We update variables step by step until we reach:
Output: trueWhy Do We Use This Approach?
A direct brute force solution is usually easier to think about, but it can become slow when the input is large. The optimized approach keeps only the important state and avoids repeated work.
That is why trie with dfs is useful for this problem.
Step-by-Step Explanation
Let us dry run the algorithm using a custom example.
Step 1
Use this custom example.
operations = addWord("bad"), addWord("dad"), search(".ad")
We will solve it using trie with dfs.
Step 2
Look at the first important value from the example and create the variables needed by the algorithm.
current_state = based on the first value
answer = not finished yet
Step 3
Move to the next useful value and update the state.
The algorithm compares the new value with the old state.
If the new value improves the answer, we update the answer.
Step 4
Continue this process until all useful values are processed.
After processing the example, we get:
Output: true
Why?
Dot can match b or d.Important Code Logic
The most important part is updating the algorithm state after reading each useful value. This is where the answer becomes better step by step.
Think like this: old_state = what we knew before current_value = value we are checking now new_state = updated result after using current_value For our example, the final state gives: Output: true
Example 1
Input:
operations = addWord("bad"), addWord("dad"), search(".ad")
Output:
Output: true
Explanation:
Dot can match b or d.Example 2
Input:
operations = addWord("cat"), addWord("car"), search("ca.")
Output:
true
Explanation:
The dot can match t or r.Python Code
Here is the complete Python solution for LeetCode #211.
class WordDictionaryNode:
def __init__(self):
self.children = {}
self.is_word = False
class WordDictionary:
def __init__(self):
self.root = WordDictionaryNode()
def add_word(self, word):
node = self.root
for char in word:
node = node.children.setdefault(char, WordDictionaryNode())
node.is_word = True
def search(self, word):
def dfs(index, node):
if index == len(word):
return node.is_word
char = word[index]
if char == ".":
return any(dfs(index + 1, child) for child in node.children.values())
if char not in node.children:
return False
return dfs(index + 1, node.children[char])
return dfs(0, self.root)
dictionary = WordDictionary()
dictionary.add_word("cat")
dictionary.add_word("car")
print(dictionary.search("cat")) # Output: True
print(dictionary.search("c.t")) # Output: True
print(dictionary.search("dog")) # Output: FalseJava Code
Here is the complete Java solution for LeetCode #211.
class WordDictionaryNode {
WordDictionaryNode[] children = new WordDictionaryNode[26];
boolean isWord;
}
class WordDictionary {
private WordDictionaryNode root = new WordDictionaryNode();
public void addWord(String word) {
WordDictionaryNode node = root;
for (char ch : word.toCharArray()) {
int index = ch - 'a';
if (node.children[index] == null) node.children[index] = new WordDictionaryNode();
node = node.children[index];
}
node.isWord = true;
}
public boolean search(String word) {
return dfs(word, 0, root);
}
private boolean dfs(String word, int index, WordDictionaryNode node) {
if (index == word.length()) return node.isWord;
char ch = word.charAt(index);
if (ch == '.') {
for (WordDictionaryNode child : node.children) {
if (child != null && dfs(word, index + 1, child)) return true;
}
return false;
}
int childIndex = ch - 'a';
return node.children[childIndex] != null && dfs(word, index + 1, node.children[childIndex]);
}
public static void main(String[] args) {
WordDictionary dictionary = new WordDictionary();
dictionary.addWord("cat");
dictionary.addWord("car");
System.out.println(dictionary.search("cat")); // true
System.out.println(dictionary.search("c.t")); // true
System.out.println(dictionary.search("dog")); // false
}
}Time and Space Complexity
Time Complexity: O(n)
The time complexity depends on how many values the algorithm needs to process and whether it uses sorting, binary search, heap, or traversal.
Space Complexity: O(n)
The extra space is used for the variables or data structures needed by the optimized approach.
Final Summary
LeetCode #211: Design Add and Search Words Data Structure becomes easier when we break it into small steps. First understand what the problem asks, then track the important state, dry run with an example, and finally write the code.