Skip to content

Instantly share code, notes, and snippets.

@CarlaTeo
Last active June 28, 2021 00:06
Show Gist options
  • Save CarlaTeo/4c13133a2d0fe1f9acf404c1364fbea7 to your computer and use it in GitHub Desktop.
Save CarlaTeo/4c13133a2d0fe1f9acf404c1364fbea7 to your computer and use it in GitHub Desktop.
[JS] Auto-complete feature using Trie
// Based on this problem: https://www.geeksforgeeks.org/auto-complete-feature-using-trie/
// We are given a Trie with a set of strings stored in it. Now the user types in a prefix of his search query, we need to give him all recommendations to auto-complete his query based on the strings stored in the Trie. We assume that the Trie stores past searches by the users.
// For example if the Trie store {“abc”, “abcd”, “aa”, “abbbaba”} and the User types in “ab” then he must be shown {“abc”, “abcd”, “abbbaba”}.
function searchAutocomplete(head, prefix) {
const words = [];
if(!prefix) return words;
let currentNode = head;
for(let letter of prefix) {
if(currentNode.children && currentNode.children[letter]) {
currentNode = currentNode.children[letter];
}
else {
return words;
}
}
getWords(currentNode, prefix, words);
return words;
}
function getWords(node, prefix, words) {
if(node.children) {
Object.keys(node.children).forEach( letter => {
const newWord = prefix + letter;
const newNode = node.children[letter];
getWords(newNode, newWord, words);
})
}
else words.push(prefix);
}
//------------------------------ Testing ------------------------------------------------//
class Node {
constructor(value) {
this.value = value;
this.children = null; // {'c': NodeC, 'b': NodeB},
}
}
const root = new Node('*');
const nodeA = new Node('a');
const nodeB = new Node('b');
const nodeF = new Node('f');
const nodeB2 = new Node('b');
const nodeA2 = new Node('a');
const nodeC = new Node('c');
const nodeD = new Node('d');
root.children = { [nodeA.value]: nodeA, [nodeB.value]: nodeB};
nodeA.children = { [nodeF.value]: nodeF, [nodeB2.value]: nodeB2};
nodeB.children = { [nodeA2.value]: nodeA2};
nodeB2.children = { [nodeC.value]: nodeC, [nodeD.value]: nodeD};
// *
// / \
// a b
// /\ \
// f b a
// / \
// c d
console.log( searchAutocomplete(root, "")); // []
console.log( searchAutocomplete(root, "h")); // []
console.log( searchAutocomplete(root, "a")); // [ 'af', 'abc', 'abd' ]
console.log( searchAutocomplete(root, "b")); // [ 'ba' ]
console.log( searchAutocomplete(root, "ab")); // [ 'abc', 'abd' ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment