Design Add and Search Words Data Structure — LeetCode 211 Python Solution
- Problem
- #211
- Pattern
- Trie
- Reading time
- 7 min
- Source
- leetcode.com
The problem
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.
Example
- Input
- ["WordDictionary","addWord","addWord","addWord","search","search","search","search"]
- Output
- [null,null,null,null,false,true,true,true]
- Explanation
- WordDictionary wordDictionary = new WordDictionary();
Python solution
class Trie:
def __init__(self):
self.children = [None] * 26
self.is_end = False
class WordDictionary:
def __init__(self):
self.trie = Trie()
def addWord(self, word: str) -> None:
node = self.trie
for c in word:
idx = ord(c) - ord('a')
if node.children[idx] is None:
node.children[idx] = Trie()
node = node.children[idx]
node.is_end = True
def search(self, word: str) -> bool:
def search(word, node):
for i in range(len(word)):
c = word[i]
idx = ord(c) - ord('a')
if c != '.' and node.children[idx] is None:
return False
if c == '.':
for child in node.children:
if child is not None and search(word[i + 1 :], child):
return True
return False
node = node.children[idx]
return node.is_end
return search(word, self.trie)
# Your WordDictionary object will be instantiated and called as such:
# obj = WordDictionary()
# obj.addWord(word)
# param_2 = obj.search(word)Complexity
| Measure | Complexity |
|---|---|
| Time | O(V+E) |
| Space | O(V) auxiliary |
Pattern: Trie
Store a set of words by their shared prefixes so lookups cost the length of the word. LeetCode 211. Design Add and Search Words Data Structure is filed here because LeetCode tags it Trie, which is the vocabulary this hub collects.
The trie guide has the Python template for the pattern and the 49 LeetCode problems that use it.
Related problems
On study lists
This problem is on Blind 75, NeetCode 150 and Top Interview 150.
Frequently asked questions
- How hard is LeetCode 211. Design Add and Search Words Data Structure?
- LeetCode 211. Design Add and Search Words Data Structure is rated Medium on LeetCode.
- What is the time complexity of LeetCode 211. Design Add and Search Words Data Structure?
- The Python solution on this page runs in O(V+E).
- What is the space complexity of LeetCode 211. Design Add and Search Words Data Structure?
- The Python solution on this page uses O(V) auxiliary space.
- What topics does LeetCode 211. Design Add and Search Words Data Structure cover?
- LeetCode 211. Design Add and Search Words Data Structure is tagged Depth-First Search, Design, Trie and String on LeetCode.