File tree Expand file tree Collapse file tree 1 file changed +49
-0
lines changed
implement-trie-prefix-tree Expand file tree Collapse file tree 1 file changed +49
-0
lines changed Original file line number Diff line number Diff line change
1
+ '''
2
+ # 208. Implement Trie (Prefix Tree)
3
+
4
+ ```
5
+ - Node structure
6
+ {children: {char: {children: { ... }, is_end: False}}, is_end: False}
7
+ ```
8
+
9
+ ## Time and Space Complexity
10
+
11
+ ```
12
+ TC: O(n)
13
+ SC: O(n)
14
+ ```
15
+
16
+ #### TC is O(n):
17
+ - insert, search, startsWith: iterating through the word just once. = O(n)
18
+
19
+ #### SC is O(n):
20
+ - insert, search, startsWith: using a hash map to store the children nodes. = O(n)
21
+ '''
22
+
23
+ class Trie :
24
+ def __init__ (self ):
25
+ self .root = {"children" : {}, "is_end" : False }
26
+
27
+ def insert (self , word : str ) -> None :
28
+ node = self .root
29
+ for char in word :
30
+ if char not in node ["children" ]:
31
+ node ["children" ][char ] = {"children" : {}, "is_end" : False }
32
+ node = node ["children" ][char ]
33
+ node ["is_end" ] = True
34
+
35
+ def search (self , word : str ) -> bool :
36
+ node = self .root
37
+ for char in word :
38
+ if char not in node ["children" ]:
39
+ return False
40
+ node = node ["children" ][char ]
41
+ return node ["is_end" ]
42
+
43
+ def startsWith (self , prefix : str ) -> bool :
44
+ node = self .root
45
+ for char in prefix :
46
+ if char not in node ["children" ]:
47
+ return False
48
+ node = node ["children" ][char ]
49
+ return True
You can’t perform that action at this time.
0 commit comments