#211

Design Add and Search Words Data Structure

Medium
StringDepth-First SearchDesignTrieTrieDepth-First Search
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

Using a Trie (prefix tree) allows us to efficiently store words and perform searches, especially with wildcards. The Trie structure enables us to traverse through characters, making it easier to handle dots as any character.

⚙️

Algorithm

3 steps
  1. 1Step 1: Create a TrieNode class to represent each node in the Trie.
  2. 2Step 2: Implement the WordDictionary class that uses the Trie for adding and searching words.
  3. 3Step 3: For searching, recursively traverse the Trie, handling dots by exploring all possible child nodes.
solution.py32 lines
1class TrieNode:
2    def __init__(self):
3        self.children = {}
4        self.is_end_of_word = False
5
6class WordDictionary:
7    def __init__(self):
8        self.root = TrieNode()
9
10    def addWord(self, word: str) -> None:
11        node = self.root
12        for char in word:
13            if char not in node.children:
14                node.children[char] = TrieNode()
15            node = node.children[char]
16        node.is_end_of_word = True
17
18    def search(self, word: str) -> bool:
19        return self._search_in_node(word, self.root)
20
21    def _search_in_node(self, word: str, node: TrieNode) -> bool:
22        for i, char in enumerate(word):
23            if char == '.':
24                for child in node.children.values():
25                    if self._search_in_node(word[i + 1:], child):
26                        return True
27                return False
28            else:
29                if char not in node.children:
30                    return False
31                node = node.children[char]
32        return node.is_end_of_word

Complexity note: The time complexity is O(n) for both adding and searching words, where n is the length of the word. The space complexity is O(n) because we store each character of the words in the Trie.

  • 1Using a Trie allows efficient prefix searching.
  • 2Handling wildcards with recursion simplifies the search process.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.