Skip to content

Commit 34bb2f1

Browse files
iamAntimPalAntim-IWPIamShiwangi
committed
Update 1268. Search Suggestions System.py
Co-Authored-By: Antim-IWP <203163676+Antim-IWP@users.noreply.github.com> Co-Authored-By: Shiwangi Srivastava <174641070+IamShiwangi@users.noreply.github.com>
1 parent 00c96ab commit 34bb2f1

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
class Trie:
2+
def __init__(self):
3+
self.children: List[Union[Trie, None]] = [None] * 26
4+
self.v: List[int] = []
5+
6+
def insert(self, w, i):
7+
node = self
8+
for c in w:
9+
idx = ord(c) - ord('a')
10+
if node.children[idx] is None:
11+
node.children[idx] = Trie()
12+
node = node.children[idx]
13+
if len(node.v) < 3:
14+
node.v.append(i)
15+
16+
def search(self, w):
17+
node = self
18+
ans = [[] for _ in range(len(w))]
19+
for i, c in enumerate(w):
20+
idx = ord(c) - ord('a')
21+
if node.children[idx] is None:
22+
break
23+
node = node.children[idx]
24+
ans[i] = node.v
25+
return ans
26+
27+
28+
class Solution:
29+
def suggestedProducts(
30+
self, products: List[str], searchWord: str
31+
) -> List[List[str]]:
32+
products.sort()
33+
trie = Trie()
34+
for i, w in enumerate(products):
35+
trie.insert(w, i)
36+
return [[products[i] for i in v] for v in trie.search(searchWord)]

0 commit comments

Comments
 (0)