Skip to content

Commit 1692ffb

Browse files
committed
Two-Hundred-Sixteen Commit: Add Search Suggestions System problem to Trie Section
1 parent db0cf43 commit 1692ffb

File tree

1 file changed

+85
-0
lines changed

1 file changed

+85
-0
lines changed
Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
package Trie;
2+
3+
// Problem Statement: Search Suggestions System (medium)
4+
// LeetCode Question: 1268. Search Suggestions System
5+
6+
import java.util.ArrayList;
7+
import java.util.List;
8+
9+
public class Problem_5_Search_Suggestions_System {
10+
11+
class TrieNode {
12+
TrieNode[] children = new TrieNode[26];
13+
boolean isEnd = false;
14+
}
15+
16+
class Trie {
17+
TrieNode root;
18+
19+
Trie() {
20+
root = new TrieNode();
21+
}
22+
23+
// Inserts a word into the trie
24+
void insert(String word) {
25+
TrieNode node = root;
26+
for (char ch : word.toCharArray()) {
27+
if (node.children[ch - 'a'] == null) {
28+
node.children[ch - 'a'] = new TrieNode();
29+
}
30+
node = node.children[ch - 'a'];
31+
}
32+
node.isEnd = true;
33+
}
34+
35+
// Performs a DFS to find all words with the given prefix
36+
void dfs(TrieNode node, List<String> list, StringBuilder word) {
37+
if (list.size() == 3) return; // Limit to 3 suggestions
38+
if (node.isEnd) {
39+
list.add(word.toString());
40+
}
41+
42+
for (char ch = 'a'; ch <= 'z'; ch++) {
43+
if (node.children[ch - 'a'] != null) {
44+
word.append(ch);
45+
dfs(node.children[ch - 'a'], list, word);
46+
word.deleteCharAt(word.length() - 1);
47+
}
48+
}
49+
}
50+
51+
// Searches the trie for words starting with prefix
52+
List<String> search(String prefix) {
53+
TrieNode node = root;
54+
List<String> list = new ArrayList<>();
55+
56+
for (char ch : prefix.toCharArray()) {
57+
if (node.children[ch - 'a'] == null) {
58+
return list; // No words found with this prefix
59+
}
60+
node = node.children[ch - 'a'];
61+
}
62+
63+
dfs(node, list, new StringBuilder(prefix));
64+
return list;
65+
}
66+
}
67+
68+
public List<List<String>> suggestedProducts(String[] products, String searchWord) {
69+
Trie trie = new Trie();
70+
for (String product : products) {
71+
trie.insert(product);
72+
}
73+
74+
List<List<String>> result = new ArrayList<>();
75+
StringBuilder prefix = new StringBuilder();
76+
77+
for (char ch : searchWord.toCharArray()) {
78+
prefix.append(ch);
79+
result.add(trie.search(prefix.toString()));
80+
}
81+
82+
return result;
83+
}
84+
85+
}

0 commit comments

Comments
 (0)