Skip to content

Commit d396841

Browse files
committed
saving words at each node for suggestion
1 parent 47c1177 commit d396841

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

Trie/searchSuggestionSystem.java

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
class Solution {
2+
/* m - avg length of product, n - length of product array
3+
Sorting strings array - O(mnlogn)
4+
TC - O(mnlogn)
5+
Building trie - O(mn)
6+
Space - O(mn + Lm) L = length of word search. (as we are constructing L genrated sublists)
7+
*/
8+
class TrieNode {
9+
TrieNode[] child;
10+
LinkedList<String> suggestion = new LinkedList<>();
11+
public TrieNode() {
12+
child = new TrieNode[26];
13+
}
14+
}
15+
16+
public void insert(String word, TrieNode root) {
17+
TrieNode cur = root;
18+
for (int i=0; i<word.length(); i++) {
19+
if (cur.child[word.charAt(i) - 'a'] == null) {
20+
cur.child[word.charAt(i) - 'a'] = new TrieNode();
21+
}
22+
cur = cur.child[word.charAt(i) - 'a'];
23+
if (cur.suggestion.size() < 3) {
24+
cur.suggestion.add(word); // put products with same prefix in the suggestion list
25+
}
26+
}
27+
}
28+
public List<List<String>> suggestedProducts(String[] products, String searchWord) {
29+
Arrays.sort(products); // sorting products array of strings
30+
31+
TrieNode root = new TrieNode();
32+
for (String p: products) {
33+
insert(p, root);
34+
}
35+
List<List<String>> res = new ArrayList<>();
36+
for (char c: searchWord.toCharArray()) {
37+
if (root != null) {
38+
root = root.child[c - 'a'];
39+
}
40+
res.add(root == null ? Arrays.asList(): root.suggestion);
41+
}
42+
return res;
43+
}
44+
}

0 commit comments

Comments
 (0)