Skip to content

Commit 46e692a

Browse files
committed
Add trie implementation
1 parent c87cc87 commit 46e692a

File tree

2 files changed

+119
-0
lines changed

2 files changed

+119
-0
lines changed

src/java1/algorithms/tree/Trie.java

+63
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
package java1.algorithms.tree;
2+
3+
import java.util.HashMap;
4+
5+
class Node {
6+
HashMap<Character, Node> children = new HashMap<>();
7+
boolean isEnd = false;
8+
}
9+
10+
public class Trie {
11+
12+
Node root;
13+
14+
Trie(){
15+
this.root = new Node();
16+
}
17+
18+
//TC: O(n) SC: O(n)
19+
public void insert(String word) {
20+
Node curr = root;
21+
for(char ch: word.toCharArray()) {
22+
if(!curr.children.containsKey(ch)) {
23+
curr.children.put(ch, new Node());
24+
}
25+
curr = curr.children.get(ch);
26+
}
27+
curr.isEnd = true;
28+
}
29+
30+
//TC: O(n) SC: O(1)
31+
public boolean search(String word) {
32+
Node curr = root;
33+
for(char ch: word.toCharArray()) {
34+
if(!(curr.children.containsKey(ch))) {
35+
return false;
36+
}
37+
curr = curr.children.get(ch);
38+
}
39+
return curr.isEnd;
40+
}
41+
42+
//TC: O(n) SC: O(1)
43+
public boolean startsWith(String prefix) {
44+
Node curr = root;
45+
for(char ch: prefix.toCharArray()) {
46+
if(!(curr.children.containsKey(ch))) {
47+
return false;
48+
}
49+
curr = curr.children.get(ch);
50+
}
51+
return true;
52+
}
53+
54+
public static void main(String[] args) {
55+
Trie trie = new Trie();
56+
trie.insert("apple");
57+
System.out.println(trie.search("apple"));
58+
System.out.println(trie.search("app"));
59+
System.out.println(trie.startsWith("app"));
60+
trie.insert("app");
61+
System.out.println(trie.search("app"));
62+
}
63+
}
+56
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
class Node {
2+
constructor() {
3+
this.children = {};
4+
this.isEnd = false;
5+
}
6+
}
7+
8+
class Trie {
9+
constructor() {
10+
this.root = new Node();
11+
}
12+
13+
//TC: O(n) SC: O(n)
14+
insert(word) {
15+
let curr = this.root;
16+
for(let ch of word) {
17+
if(!(ch in curr.children)) {
18+
curr.children[ch] = new Node();
19+
}
20+
curr = curr.children[ch];
21+
}
22+
curr.isEnd = true;
23+
}
24+
25+
//TC: O(n) SC: O(1)
26+
search(word) {
27+
let curr = this.root;
28+
for(let ch of word) {
29+
if(!(ch in curr.children)) {
30+
return false;
31+
}
32+
curr = curr.children[ch];
33+
}
34+
return curr.isEnd;
35+
}
36+
37+
//TC: O(n) SC: O(1)
38+
startsWith(prefix) {
39+
let curr = this.root;
40+
for(let ch of prefix) {
41+
if(!(ch in curr.children)) {
42+
return false;
43+
}
44+
curr = curr.children[ch];
45+
}
46+
return true;
47+
}
48+
}
49+
50+
let trie = new Trie();
51+
trie.insert("apple");
52+
console.log(trie.search("apple"));
53+
console.log(trie.search("app"));
54+
console.log(trie.startsWith("app"));
55+
trie.insert("app");
56+
console.log(trie.search("app"));

0 commit comments

Comments
 (0)