Created
November 24, 2021 08:28
-
-
Save cagataycali/6342fa472d992c99f253f7f566a6c4bb to your computer and use it in GitHub Desktop.
[Trie] Prefix tree for find auto complete suggestions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Node { | |
constructor(char) { | |
this.char = char; | |
this.children = new Map(); // It's limited by 26 chars, hashmap. | |
this.isEndWord = false; | |
} | |
} | |
class Trie { | |
constructor() { | |
this.root = new Node(""); | |
} | |
insert(...words) { | |
// insert the word | |
for (const word of words) { | |
let node = this.root; | |
for (const char of word) { | |
if (!node.children.has(char)) { | |
node.children.set(char, new Node(char)); | |
} | |
node = node.children.get(char); | |
} | |
node.isEndWord = true; | |
} | |
} | |
search(word) { | |
let found = true; | |
let node = this.root; | |
for (const char of word) { | |
// If we do not have that char in our prefix tree. | |
if (!node.children.has(char)) { | |
found = false; | |
break; | |
} | |
node = node.children.get(char); | |
} | |
return node && node.isEndWord && found; | |
} | |
autocomplete(word) { | |
const suggestions = []; | |
let node = this.root; | |
for (const char of word) { | |
if (!node.children.has(char)) { | |
return suggestions; | |
} | |
node = node.children.get(char); | |
} | |
this.autocompleteHelper( | |
node, | |
suggestions, | |
word.substring(0, word.length - 1) | |
); | |
return suggestions; | |
} | |
autocompleteHelper(node, suggestions, prefix) { | |
if (node.isEndWord) { | |
suggestions.push(prefix + node.char); | |
} | |
for (const child of node.children.keys()) { | |
// in returns key of hashmap. | |
const childNode = node.children.get(child); | |
this.autocompleteHelper(childNode, suggestions, prefix + node.char); | |
} | |
} | |
} | |
const prefixTree = new Trie(); | |
prefixTree.insert("amz", "am", "amazon"); | |
prefixTree.search("am"); // returns true | |
console.log(prefixTree.autocomplete("a")); // returns ['am', 'amz', 'amazon'] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment