AniUI Academy

A trie for an autocomplete box

mediumData Structures+250 XPPractice

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");       // true

A 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 word

What 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.
  • has is true only for full inserted words, while startsWith is true for any stored prefix.
  • Inserting the same word twice does not duplicate it in the results.

Notes

  • insert, has, and startsWith run in O(L), where L is the length of the word or prefix — independent of how many words are stored.
  • complete is 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 from startsWith('react').
Asked atGoogleMetaAmazon

Stuck? The javascript course covers everything this challenge needs.

Try it yourself
Loading playground...
5 tests · +250 XP

Discussion

Sign in to post
Sign in to join the conversation.Sign in

No comments yet. Be the first to say something.