Implement Trie (Prefix Tree)
Module 20 · Tries
Problem
Implement a Trie class with three methods:
insert(word)— addwordto the trie.search(word)— returntrueifwordwas inserted (exactly), elsefalse.startsWith(prefix)— returntrueif any inserted word begins withprefix, elsefalse.
Examples
Example 1
insert("apple"), search("apple")OutputtrueExample 2
search("app")OutputfalseExplanation. "app" was never inserted as a word
Example 3
startsWith("app")OutputtrueExplanation. but apple starts with "app"
Example 4
insert("app"), search("app")OutputtrueExplanation. now it has been
Constraints
words and prefixes are lowercase English letters, 1–2000 characters; up to 3·10⁴ calls total across the three methods.
Attempt it first
This is the concept lesson made into an interface — build it yourself
before reading on. The one thing to get exactly right is the difference
between search and startsWith: the search("app") → false line in
the example above is the entire test. If your search returns true
for "app" after only "apple" was inserted, you've forgotten the
is_end_of_word flag. Write all three methods and trace that example by
hand.