Implement Trie
Design a Trie (prefix tree) supporting three operations: insert(word) adds a word; search(word) returns true only if the exact word was inserted; startsWith(prefix) returns true if any inserted word begins with the given prefix.
Open official problem prompt ↗Build a dictionary structure that answers both exact-word and prefix-existence queries in time proportional to the query length, independent of how many words are stored.
Like a physical library index where each drawer is a letter: to file or find a word you follow drawer 'a', then 'p', then 'p'... and a small flag on a drawer means 'a complete word ends here', not just 'more words continue past here'.
- Input
- insert("apple"); search("apple"); search("app"); startsWith("app"); insert("app"); search("app")
- Output
- [null, true, false, true, null, true]
- Why
- 'apple' is present so search('apple') is true; 'app' was not inserted yet so search('app') is false but startsWith('app') is true; after inserting 'app', search('app') becomes true.
1 <= word.length, prefix.length <= 2000word and prefix consist only of lowercase English lettersAt most 3 * 10^4 calls in total to insert, search, and startsWith