Skip to content
Decoder

Implement Trie (Prefix Tree)

Medium

Problem

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.

Example 1

trie = Trie()

Example 2

trie.insert("apple")

Example 3

Input
trie.search("apple")
Output
True

Example 4

Input
trie.search("app")
Output
False
Why
only a prefix so far

Example 5

Input
trie.starts_with("app")
Output
True

Example 6

trie.insert("app")

Example 7

Input
trie.search("app")
Output
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.

Read it once before you touch anything

Want some pressure? Start the timer. In an interview you get about two minutes to understand the problem.

  1. 1Read the goalWhat goes in, what comes out
  2. 2Scan the examplesCheck one by hand
  3. 3Note the constraintsThey set your Big O
Say what it asks in one sentence
Say it out loud first, then compare with ours.