211. Design Add and Search Words Data Structure
MediumSolutions in Python, Java, C++, TypeScript
Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.
Approach
The problem requires us to implement a data structure that can store words and efficiently search for them. The search functionality is special because it supports a wildcard character '.' that can match any single letter. This requirement suggests that a simple hash set would not be sufficient, as we need to handle pattern matching, not just exact string matching.
Solution
Design Add and Search Words Data Structure in Python
class WordDictionary:
def __init__(self):
"""
Initializes the data structure.
Using a nested dictionary to represent the Trie.
A special key '#' is used to mark the end of a word.
"""
self.trie = {}
def addWord(self, word: str) -> None:
"""Adds a word into the data structure."""
node = self.trie
for char in word:
# setdefault returns the value of a key if it is in the dictionary.
# If not, it inserts key with a value to the dictionary and returns it.
node = node.setdefault(char, {})
node['#'] = True # Mark the end of the word
def search(self, word: str) -> bool:
"""
Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter.
"""
def dfs(node, index):
# Base case: if we have checked all characters in the word
if index == len(word):
return '#' in node
char = word[index]
if char == '.':
# If wildcard, iterate through all possible next characters
for key in node:
if key != '#' and dfs(node[key], index + 1):
return True
return False
else:
# If a regular character, check if path exists
if char not in node:
return False
return dfs(node[char], index + 1)
return dfs(self.trie, 0)
# Your WordDictionary object will be instantiated and called as such:
# obj = WordDictionary()
# obj.addWord(word)
# param_2 = obj.search(word)
Design Add and Search Words Data Structure in Java
class WordDictionary {
private class TrieNode {
TrieNode[] children;
boolean isEndOfWord;
public TrieNode() {
children = new TrieNode[26];
isEndOfWord = false;
}
}
private final TrieNode root;
public WordDictionary() {
root = new TrieNode();
}
public void addWord(String word) {
TrieNode current = root;
for (char c : word.toCharArray()) {
int index = c - 'a';
if (current.children[index] == null) {
current.children[index] = new TrieNode();
}
current = current.children[index];
}
current.isEndOfWord = true;
}
public boolean search(String word) {
return searchInNode(word, 0, root);
}
private boolean searchInNode(String word, int index, TrieNode node) {
if (node == null) {
return false;
}
if (index == word.length()) {
return node.isEndOfWord;
}
char ch = word.charAt(index);
if (ch == '.') {
// If the character is a dot, try all possible children
for (int i = 0; i < 26; i++) {
if (searchInNode(word, index + 1, node.children[i])) {
return true;
}
}
return false;
} else {
// If it's a letter, move to the specific child
int childIndex = ch - 'a';
return searchInNode(word, index + 1, node.children[childIndex]);
}
}
}
/**
* Your WordDictionary object will be instantiated and called as such:
* WordDictionary obj = new WordDictionary();
* obj.addWord(word);
* boolean param_2 = obj.search(word);
*/
Design Add and Search Words Data Structure in C++
class WordDictionary {
private:
struct TrieNode {
TrieNode* children[26];
bool isEndOfWord;
TrieNode() {
isEndOfWord = false;
for (int i = 0; i < 26; ++i) {
children[i] = nullptr;
}
}
};
TrieNode* root;
bool searchInNode(const string& word, int index, TrieNode* node) {
if (!node) {
return false;
}
if (index == word.length()) {
return node->isEndOfWord;
}
char ch = word[index];
if (ch == '.') {
// If the character is a dot, try all possible children
for (int i = 0; i < 26; ++i) {
if (searchInNode(word, index + 1, node->children[i])) {
return true;
}
}
return false;
} else {
// If it's a letter, move to the specific child
int childIndex = ch - 'a';
return searchInNode(word, index + 1, node->children[childIndex]);
}
}
public:
WordDictionary() {
root = new TrieNode();
}
void addWord(string word) {
TrieNode* current = root;
for (char ch : word) {
int index = ch - 'a';
if (!current->children[index]) {
current->children[index] = new TrieNode();
}
current = current->children[index];
}
current->isEndOfWord = true;
}
bool search(string word) {
return searchInNode(word, 0, root);
}
};
/**
* Your WordDictionary object will be instantiated and called as such:
* WordDictionary* obj = new WordDictionary();
* obj->addWord(word);
* bool param_2 = obj->search(word);
*/
Design Add and Search Words Data Structure in TypeScript
class WordDictionary {
// The root of the Trie, represented by a plain object.
private root: any;
constructor() {
// Each node is an object. Keys are characters, values are child nodes.
// A special property 'isEnd' marks the end of a word.
this.root = {};
}
addWord(word: string): void {
let node = this.root;
for (const char of word) {
if (!node[char]) {
node[char] = {};
}
node = node[char];
}
node.isEnd = true;
}
search(word: string): boolean {
// Helper function to perform DFS search.
const dfs = (node: any, index: number): boolean => {
// Base case: if we've processed the entire word
if (index === word.length) {
// Check if it's the end of a valid word
return !!node.isEnd;
}
const char = word[index];
if (char === '.') {
// If wildcard, check all possible paths
for (const key in node) {
// 'isEnd' is not a character path
if (key !== 'isEnd') {
if (dfs(node[key], index + 1)) {
return true;
}
}
}
return false;
} else {
// If a specific character, follow that path
if (!node[char]) {
return false;
}
return dfs(node[char], index + 1);
}
};
return dfs(this.root, 0);
}
}
/**
* Your WordDictionary object will be instantiated and called as such:
* var obj = new WordDictionary()
* obj.addWord(word)
* var param_2 = obj.search(word)
*/
More Medium LeetCode answers
Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.
LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.