A trie for an autocomplete box
Autocomplete over a big list of commands, tags or city names gets slow if every keystroke filters the entire array. A trie stores words character by character so a prefix lookup walks only as far as the prefix is long.
Implement a Trie class. It is constructed with no arguments and starts empty. insert(word) stores a lowercase word; inserting the same word twice has no additional effect and its return value is not used. has(word) returns true only when that exact word was inserted, and false for a mere prefix of one. startsWith(prefix) returns true when at least one stored word begins with the prefix. complete(prefix) returns an array of every stored word beginning with the prefix, sorted alphabetically ascending, and returns [] when nothing matches. A word counts as beginning with itself, and complete('') returns every stored word.
Examples
const t = new Trie();
["react", "redux", "refactor", "vue"].forEach((w) => t.insert(w));
t.complete("re");
// ["react", "redux", "refactor"]const t = new Trie();
t.insert("react");
t.has("rea"); // false — a prefix, not a word
t.startsWith("rea"); // true
t.has("react"); // trueA stored word is different from a stored prefix.
const t = new Trie();
t.insert("form");
t.insert("format");
t.complete("form"); // ["form", "format"] — prefix is itself a wordWhat it has to do
complete(prefix)returns matching words sorted alphabetically ascending.complete(prefix)includes the prefix itself when it was inserted as a word.complete(prefix)returns[]when no word matches.hasistrueonly for full inserted words, whilestartsWithistruefor any stored prefix.- Inserting the same word twice does not duplicate it in the results.
Notes
insert,has, andstartsWithrun in O(L), where L is the length of the word or prefix — independent of how many words are stored.completeis O(L + m), where m is the total characters across the matches it has to collect. The alphabetical sort adds O(k log k) over the k matches found.- Each node needs a map of children plus a marker for 'a word ends here'. Without the marker, you cannot tell
has('react')apart fromstartsWith('react').
Stuck? The javascript course covers everything this challenge needs.
- 1.completes a prefix in alphabetical order
- 2.distinguishes a stored word from a stored prefix
- 3.an empty prefix returns every word
- 4.a prefix that is itself a word is included
- 5.an empty trie matches nothing and repeats do not duplicate
These assertions run in your browser the moment you hit Run. Pass all of them to claim the XP.
Discussion
Sign in to postNo comments yet. Be the first to say something.