-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPrefixTrie.js
More file actions
64 lines (58 loc) · 1.8 KB
/
PrefixTrie.js
File metadata and controls
64 lines (58 loc) · 1.8 KB
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
60
61
62
63
64
class PrefixTrieNode {
constructor() {
this.children = {};
this.isEnd = false;
}
}
class PrefixTrie {
constructor() {
this.root = new PrefixTrieNode();
}
// O(n) time, where n - word.length
insert(word) {
let currentNode = this.root;
for (let i = 0; i < word.length; i++) {
const currentChar = word[i];
if (!currentNode.children[currentChar]) {
currentNode.children[currentChar] = new PrefixTrieNode();
}
currentNode = currentNode.children[currentChar];
}
currentNode.isEnd = true;
}
// O(n) time, where n - word.length
search(word) {
let currentNode = this.root;
for (let i = 0; i < word.length; i++) {
const currentChar = word[i];
if (!currentNode.children[currentChar]) {
return false;
}
currentNode = currentNode.children[currentChar];
}
return currentNode.isEnd;
}
// O(n) time, where n - prefix.length
startsWith(prefix) {
let currentNode = this.root;
for (let i = 0; i < prefix.length; i++) {
const currentChar = prefix[i];
if (!currentNode.children[currentChar]) {
return false;
}
currentNode = currentNode.children[currentChar];
}
return true;
}
}
module.exports = { PrefixTrieNode, PrefixTrie };
// usage example
const trie = new PrefixTrie();
trie.insert('banana');
trie.insert('bandana');
console.log(trie.search('banana')); // true
console.log(trie.search('bandana')); // true
console.log(trie.search('ban')); // false
console.log(trie.startsWith('ban')); // true
console.log(trie.startsWith('band')); // true
console.log(trie.startsWith('foo')); // false