Skip to content

Instantly share code, notes, and snippets.

@carefree-ladka
Created August 7, 2024 09:11
Show Gist options
  • Select an option

  • Save carefree-ladka/4110af5c76a34c25b17b83dd02d6cb10 to your computer and use it in GitHub Desktop.

Select an option

Save carefree-ladka/4110af5c76a34c25b17b83dd02d6cb10 to your computer and use it in GitHub Desktop.
Autocomplete Feature using Trie
class TrieNode {
constructor() {
this.children = {};
this.isEndOfWord = false;
this.word = null; // Store the complete word ending at this node
}
}
class Trie {
constructor() {
this.root = new TrieNode();
}
insert(word) {
let node = this.root;
for (const char of word) {
if (!node.children[char]) {
node.children[char] = new TrieNode();
}
node = node.children[char];
}
node.isEndOfWord = true;
node.word = word; // Store the complete word
}
searchPrefix(prefix) {
let node = this.root;
for (const char of prefix) {
if (!node.children[char]) {
return null; // Prefix not found
}
node = node.children[char];
}
return node; // Node where the prefix ends
}
collectWords(node, words) {
if (node.isEndOfWord) {
words.push(node.word);
}
for (const char in node.children) {
this.collectWords(node.children[char], words);
}
}
findWordsWithPrefix(prefix) {
const node = this.searchPrefix(prefix);
const words = [];
if (node) {
this.collectWords(node, words);
}
return words;
}
}
// Example usage
const words = ['apple', 'banana', 'apricot', 'berry', 'avocado', 'cherry'];
const prefix = 'ap';
const trie = new Trie();
words.forEach(word => trie.insert(word));
const result = trie.findWordsWithPrefix(prefix);
console.log(result); // Output: ['apple', 'apricot']
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment