A trie (pronounced as "try") or prefix tree is a specialized tree data structure that efficiently stores and retrieves strings. Think of it as a digital dictionary where each path from root to node represents a sequence of characters.
Tries are incredibly useful for applications like:
- Autocomplete systems (like Google search suggestions)
- Spell checkers (finding words with common prefixes)
- IP routing (longest prefix matching)
- T9 predictive text
Your task is to implement a Trie class with these core operations:
Trie()- Initialize an empty trieinsert(word)- Add a word to the triesearch(word)- Check if a complete word existsstartsWith(prefix)- Check if any word starts with the given prefix
Example: After inserting "cat", "cats", and "dog", searching for "cat" returns true, but searching for "ca" returns false. However, startsWith("ca") returns true because "cat" and "cats" start with "ca".
Input & Output
Visualization
Time & Space Complexity
Where m is the length of the word/prefix. Each operation traverses at most m nodes in the tree.
In worst case, where N is number of words, M is average length, and ALPHABET_SIZE is typically 26 for lowercase letters. Common prefixes are shared.
Constraints
- 1 โค word.length, prefix.length โค 2000
- word and prefix consist of only lowercase English letters
- At most 3 ร 104 calls will be made to insert, search, and startsWith
- All input strings are non-empty for insert and search operations