-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
0208-implement-trie-prefix-tree.js
59 lines (45 loc) · 1.17 KB
/
0208-implement-trie-prefix-tree.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
/**
* Your Trie object will be instantiated and called as such:
* var obj = new Trie()
* obj.insert(word)
* var param_2 = obj.search(word)
* var param_3 = obj.startsWith(prefix)
*/
class TrieNode {
constructor() {
this.children = {};
this.isWord = false;
}
}
class Trie {
constructor() {
this.root = new TrieNode();
}
/* Time O(N) | Space O(N) */
insert(word, node = this.root) {
for (const char of word) {
const child = node.children[char] || new TrieNode();
node.children[char] = child;
node = child;
}
node.isWord = true;
}
/* Time O(N) | Space O(1) */
search(word, node = this.root) {
for (const char of word) {
const child = node.children[char] || null;
if (!child) return false;
node = child;
}
return node.isWord;
}
/* Time O(N) | Space O(1) */
startsWith(prefix, node = this.root) {
for (const char of prefix) {
const child = node.children[char] || null;
if (!child) return false;
node = child;
}
return true;
}
}