chore(JavaScript): add trie implementations algorithm (#863)

Co-authored-by: Ming Tsai <37890026+ming-tsai@users.noreply.github.com>
pull/963/head
Gaurav Bhardwaj 2022-10-06 20:53:19 +05:30 committed by GitHub
parent 9b6d8e0b77
commit 684d69de08
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 83 additions and 0 deletions

View File

@ -49,3 +49,7 @@
- [Max Heap](src/heaps/max-heap.js)
- [Min Heap](src/heaps/min-heap.js)
## Trie
- [Trie Implementation](src/trie/trie-implementation.js)

View File

@ -0,0 +1,79 @@
/*
A trie (pronounced as "try") or prefix tree is a tree data structure
used to efficiently store and retrieve keys in a dataset of strings.
There are various applications of this data structure,
such as autocomplete and spellchecker.
Insertion:
Average Case: O(N)
Worst Case: O(N)
Best Case: O(N)
Deletion:
Average Case: O(N)
Worst Case: O(N)
Best Case: O(N)
Searching:
Average Case: O(N)
Worst Case: O(N)
Best Case: O(1)
Space complexity: O(alphabet_size * average key length * N)
*/
/*
Create a node that will have two properties
one is the hash map for storing children.
the other one is for keeping track of the end of the word.
*/
class Node {
constructor() {
this.children = {};
this.isEndWord = false;
}
}
class Trie {
constructor() {
this.root = new Node();
}
insert(word) {
let node = this.root;
for (const char of word) {
if (!node.children[char]) {
node.children[char] = new Node();
}
node = node.children[char];
}
node.isEndWord = true;
}
search(word) {
let node = this.root;
for (const char of word) {
if (!node.children[char]) {
return false;
}
node = node.children[char];
}
return node.isEndWord ? true : false;
}
startsWith(prefix) {
let node = this.root;
for (const char of prefix) {
if (!node.children[char]) {
return false;
}
node = node.children[char];
}
return true;
}
}
const trie = new Trie();
trie.insert('datastructures');
trie.insert('datablock');
console.log(trie.search('dsa')); // false
console.log(trie.search('datablock')); // true
console.log(trie.startsWith('data')); // true