Skip to content

Commit e8ee61d

Browse files
committed
Implement Trie Prefix Tree
1 parent 02fdf7a commit e8ee61d

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
class TrieNode {
2+
TrieNode[] children;
3+
boolean isEndOfWord;
4+
5+
public TrieNode() {
6+
children = new TrieNode[26];
7+
isEndOfWord = false;
8+
}
9+
}
10+
11+
class Trie {
12+
13+
private TrieNode root;
14+
15+
public Trie() {
16+
root = new TrieNode();
17+
}
18+
19+
// TC: O(n)
20+
// SC: O(n * m)
21+
// -> word length * new TrieNode spaces
22+
public void insert(String word) {
23+
TrieNode node = root;
24+
for (char c : word.toCharArray()) {
25+
int idx = c - 'a';
26+
if (node.children[idx] == null) {
27+
node.children[idx] = new TrieNode();
28+
}
29+
node = node.children[idx];
30+
}
31+
node.isEndOfWord = true;
32+
}
33+
34+
// TC: O(n)
35+
// SC: O(1)
36+
public boolean search(String word) {
37+
TrieNode node = searchPrefix(word);
38+
return node != null && node.isEndOfWord;
39+
}
40+
41+
// TC: O(n)
42+
// SC: O(1)
43+
private TrieNode searchPrefix(String word) {
44+
TrieNode node = root;
45+
for (char c : word.toCharArray()) {
46+
int idx = c - 'a';
47+
if (node.children[idx] == null) return null;
48+
node = node.children[idx];
49+
}
50+
return node;
51+
}
52+
53+
public boolean startsWith(String prefix) {
54+
return searchPrefix(prefix) != null;
55+
}
56+
}

0 commit comments

Comments
 (0)