Implement Trie (Prefix Tree)

Medium Tries

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

Calls:
Trie()
insert("tea")
search("tea") → true
search("te") → false
startsWith("te") → true
insert("te")
search("te") → true

te only begins tea, so search says false and startsWith says true; once te is inserted too, search finds it.

Example 2

Calls:
Trie()
search("ox") → false
startsWith("o") → false
insert("ocean")
startsWith("ocean") → true
startsWith("oceans") → false
search("oce") → false

Example 3

Calls:
Trie()
insert("go")
insert("go")
insert("gopher")
search("go") → true
startsWith("gop") → true
search("gophers") → false
search("gopher") → true

Constraints

  • 1 ≤ word.length ≤ 12 and 1 ≤ prefix.length ≤ 12
  • word and prefix hold only lowercase English letters
  • at most 10⁵ calls in all to insert, search and startsWith

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.

See the AI round

More Tries

All Tries problems