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

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

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
All Tries problems