Skip to content

Commit 13f14cc

Browse files
committed
solve: designAddAndSearchWordsDataStructure
1 parent 117c6d4 commit 13f14cc

File tree

1 file changed

+43
-0
lines changed
  • design-add-and-search-words-data-structure

1 file changed

+43
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
# Time Complexity: O(n) - where n is the length of the word(addWord)
2+
# Space Complexity: O(N) - where N is the total number of characters inserted
3+
4+
class WordDictionary:
5+
def __init__(self):
6+
# using a trie (prefix tree) to store all the words
7+
self.trie = dict()
8+
9+
def addWord(self, word: str) -> None:
10+
# start from the root of the trie
11+
trie = self.trie
12+
for letter in word:
13+
# if this letter isn't already in the current trie level, add it
14+
if letter not in trie:
15+
trie[letter] = dict()
16+
# move one level deeper
17+
trie = trie[letter]
18+
# mark the end of the word with a special null character
19+
trie['\0'] = dict()
20+
21+
def internal_search(self, trie: dict, index: int, word: str) -> bool:
22+
if index == len(word):
23+
# check if this path ends a valid word
24+
return '\0' in trie
25+
26+
letter = word[index]
27+
28+
# if hit a '.', gotta try all possible paths from here
29+
if letter == '.':
30+
for child in trie.values():
31+
if self.internal_search(child, index + 1, word):
32+
return True
33+
return False
34+
else:
35+
# if the letter exists in the current trie level, keep going
36+
if letter in trie:
37+
return self.internal_search(trie[letter], index + 1, word)
38+
else:
39+
return False
40+
41+
def search(self, word: str) -> bool:
42+
# start the recursive search from index 0 and the root
43+
return self.internal_search(self.trie, 0, word)

0 commit comments

Comments
 (0)