Implement Trie (Prefix Tree)
MediumNeetCode 150Top Interview 150 TriesMongoDBXDocusignProblem
A trie is a tree that stores words one letter per edge, so words that share a beginning share a path.
Build a class Trie with these operations:
Trie()creates an empty trie.insert(word)storesword.search(word)returnstrueonly if exactlywordwas inserted earlier.startsWith(prefix)returnstrueif any inserted word begins withprefix.
The input is a list of calls and their arguments; the output lists what each call returns
(null for the constructor and for insert).
Constraints
- 1 ≤ word.length, prefix.length ≤ 2000
- word and prefix use only lowercase English letters
- At most 3 · 10⁴ calls in total
Examples: pick one to animate
Solutions
Time: insert, search and startsWith each walk one edge per letter of the argument, L letters in all.
Space: Each inserted word adds at most one new node per letter, and shared prefixes are stored once.
Every node holds a map from a letter to its child and a flag that says "a word ends here".
insert walks the letters, creating missing children, then sets the flag.
search and startsWith share one helper that walks the letters and returns the node it
reaches (or null); search also needs the flag, startsWith does not.