← All Exercises
Trie Prefix Autocomplete
intermediatejavascript
Background
Tries give prefix queries in time proportional to the prefix length, which is why search boxes, IDE completions, and IP routing tables use them.
Problem
Build a trie from a word list. For a query prefix, return every inserted word that starts with that prefix, sorted in lexicographic order. The output must also work for the empty prefix, which returns all words.
Input
A JSON object {"words": string[], "prefix": string} of lowercase words with no duplicates.Output
A JSON object {"matches": string[]} in lexicographic order.Sample tests
Sample 1
Input: {"words":["tree","trie","try","trip","ten"],"prefix":"tr"}Expected: {"matches":["tree","trie","trip","try"]}Sample 2
Input: {"words":["a","ab","abc"],"prefix":""}Expected: {"matches":["a","ab","abc"]}Sample 3
Input: {"words":["cat","car","dog"],"prefix":"ca"}Expected: {"matches":["car","cat"]}Your solution
Learning objective
Implement trie insertion, prefix descent, and ordered DFS enumeration.