Skip to content

Commit 04a8b21

Browse files
committed
implement trie prefix tree solution
1 parent 96a81aa commit 04a8b21

1 file changed

Lines changed: 52 additions & 0 deletions

File tree

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
# TC: O(L)
2+
# SC: O(L * N)
3+
class TrieNode:
4+
def __init__(self):
5+
self.next = {}
6+
self.is_end = False
7+
8+
class Trie:
9+
10+
def __init__(self):
11+
self.root = TrieNode()
12+
13+
def insert(self, word: str) -> None:
14+
cur = self.root
15+
16+
for c in word:
17+
if c not in cur.next:
18+
cur.next[c] = TrieNode()
19+
20+
cur = cur.next[c]
21+
22+
cur.is_end = True
23+
24+
def search(self, word: str) -> bool:
25+
cur = self.root
26+
27+
for c in word:
28+
if c not in cur.next:
29+
return False
30+
31+
cur = cur.next[c]
32+
33+
return cur.is_end
34+
35+
def startsWith(self, prefix: str) -> bool:
36+
cur = self.root
37+
38+
for c in prefix:
39+
if c not in cur.next:
40+
return False
41+
42+
cur = cur.next[c]
43+
44+
return True
45+
46+
47+
# Your Trie object will be instantiated and called as such:
48+
# obj = Trie()
49+
# obj.insert(word)
50+
# param_2 = obj.search(word)
51+
# param_3 = obj.startsWith(prefix)
52+

0 commit comments

Comments
 (0)