This practice workspace is built for desktop. Open it on a larger screen to start solving.
Implement Trie (Prefix Tree)
A trie (pronounced as "try") or prefix tree is a tree data structure used to efficiently store and retrieve keys in a dataset of strings. There are various applications of this data structure, such as autocomplete and spellchecker.
Implement the Trie class:
Trie()Initializes the trie object.insert(word)Inserts the stringwordinto the trie.search(word)Returnstrueif the stringwordis in the trie (i.e., was inserted before), andfalseotherwise.startsWith(prefix)Returnstrueif there is a previously inserted string that hasprefixas a prefix, andfalseotherwise.
Testing harness — dispatcher convention
Because the test runner invokes a single function rather than instantiating a class, you must expose your Trie through a dispatcher named trieOperations(operations). operations is an array of [op, ...args] tuples. The dispatcher constructs a fresh Trie and returns an array of results, one per operation:
- For
['insert', word], pushnull. - For
['search', word], push the boolean result. - For
['startsWith', prefix], push the boolean result.
Example:
function trieOperations(operations) {
const trie = new Trie();
const results = [];
for (const [op, ...args] of operations) {
if (op === 'insert') { trie.insert(args[0]); results.push(null); }
else if (op === 'search') { results.push(trie.search(args[0])); }
else if (op === 'startsWith') { results.push(trie.startsWith(args[0])); }
}
return results;
}
So a test input like [['insert','apple'], ['search','apple'], ['search','app'], ['startsWith','app'], ['insert','app'], ['search','app']] should return [null, true, false, true, null, true].
Examples
Constraints
- 1 <= word.length, prefix.length <= 2000
- word and prefix consist only of lowercase English letters.
- At most 3 * 10^4 calls in total will be made to insert, search, and startsWith.
Preview Mode
This is a read-only preview of DSAMind's AI coaching. Sign up to get custom feedback on your own solution.
Your approach
- Pattern:Trie
- Time:O(N)
- Space:O(1)
Complete approach — pattern and complexity both named.
Coach
What you got right
You correctly matched the sorted input requirement and implemented a linear-time scan using two pointers.
Where it diverged
No divergence detected. The code correctly aligns with the stated approach.
Next attempt: focus on
Try solving related sliding window problems to build familiarity with two-pointer variants.
Signals
No signals fired — clean run, you stayed in flow.