Skip to content

Commit 1f96e6f

Browse files
committed
add solution: implement-trie-prefix-tree
1 parent a889ab8 commit 1f96e6f

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed

implement-trie-prefix-tree/dusunax.py

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
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

0 commit comments

Comments
 (0)