Skip to content

Implement Trie (Prefix Tree)

MediumTrees
Decode it first. Clues, constraints, pattern and plan before any code.

A trie (say "try", also called a prefix tree) stores strings one character per level, so words that share a beginning share a path. It is what powers autocomplete and spell checkers.

Build a class Trie with:

  • insert(word): add word to the trie.
  • search(word): return True if word was inserted as a whole word.
  • starts_with(prefix) (startsWith in TypeScript): return True if any inserted word begins with prefix.
trie = Trie()
trie.insert("apple")
trie.search("apple")      →  True
trie.search("app")        →  False   (only a prefix so far)
trie.starts_with("app")   →  True
trie.insert("app")
trie.search("app")        →  True

Constraints

  • 1 <= word.length, prefix.length <= 2000
  • word and prefix consist only of lowercase English letters.
  • At most 3 * 10^4 calls in total to insert, search and starts_with.