File tree Expand file tree Collapse file tree 1 file changed +67
-0
lines changed
design-add-and-search-words-data-structure Expand file tree Collapse file tree 1 file changed +67
-0
lines changed Original file line number Diff line number Diff line change 1+ '''
2+ # 211. Design Add and Search Words Data Structure
3+
4+ use trie to perform add and search operations on words.
5+ use recursive dfs to search for words with "." wildcards.
6+
7+ ## Time and Space Complexity
8+
9+ ### addWord
10+
11+ ```
12+ TC: O(n)
13+ SC: O(n)
14+ ```
15+
16+ ### TC is O(n):
17+ - iterating through each character of the word. = O(n)
18+
19+ ### SC is O(n):
20+ - storing the word in the trie. = O(n)
21+
22+ ### search
23+
24+ ```
25+ TC: O(n)
26+ SC: O(n)
27+ ```
28+
29+ ### TC is O(n):
30+ - dfs iterates through each character of the word. = O(n)
31+ - if char is "."(wildcard) dfs iterates through all children of the current node. = O(n)
32+
33+ > recursion for the wildcard could involve exploring several paths.
34+ > but time complexity is bounded by the length of the word, so it's still O(n).
35+
36+ ### SC is O(n):
37+ - length of the word as recursive call stack. = O(n)
38+ '''
39+ class WordDictionary :
40+ def __init__ (self ):
41+ self .trie = {}
42+
43+ def addWord (self , word : str ) -> None :
44+ node = self .trie
45+ for char in word : # TC: O(n)
46+ if char not in node :
47+ node [char ] = {}
48+ node = node [char ]
49+ node ["$" ] = True
50+
51+ def search (self , word : str ) -> bool :
52+ def dfs (node , i ) -> bool :
53+ if not isinstance (node , dict ):
54+ return False
55+ if i == len (word ):
56+ return "$" in node if isinstance (node , dict ) else False
57+ char = word [i ]
58+
59+ if char == "." :
60+ for child in node .values ():
61+ if dfs (child , i + 1 ):
62+ return True
63+ return False
64+ else :
65+ return dfs (node [char ], i + 1 ) if char in node else False
66+
67+ return dfs (self .trie , 0 )
You can’t perform that action at this time.
0 commit comments