Implement Trie (Prefix Tree)
Medium Tries AI round
Trie() keeps a collection of words, empty to begin with, and answers questions about the words in it and how they begin.
insert(word) adds word to the collection. Adding a word that is already in it changes nothing.
search(word) returns true when word was inserted as a whole word, and false otherwise. A word that only begins an inserted word is not found by it.
startsWith(prefix) returns true when some inserted word begins with prefix, and false otherwise. A whole word counts as beginning with itself.
Example 1
te only begins tea, so search says false and startsWith says true; once te is inserted too, search finds it.
Example 2
Example 3
Constraints
1 ≤ word.length ≤ 12and1 ≤ prefix.length ≤ 12wordandprefixhold only lowercase English letters- at most
10⁵calls in all toinsert,searchandstartsWith
Practice this in an AI round
30 minutes on this problem with an AI agent beside your code, then a report on your solution and how you used the agent.
Your first AI round is free.
More Tries
- Word BreakAI round · Medium
- Word Search IIAI round · Hard
- Longest Common PrefixEasy
- Design Add and Search Words Data StructureMedium
- Top K Frequent WordsMedium