A trie (pronounced as "try") or prefix tree is a tree data structure used to efficiently store and retrieve keys in a dataset of strings. There are various applications of this data structure, such as autocomplete and spellchecker.
Implement the Trie class:
Trie() Initializes the trie object.void insert(String word) Inserts the string word into the trie.boolean search(String word) Returns true if the string word is in the trie (i.e., was inserted before), and false otherwise.boolean startsWith(String prefix) Returns true if there is a previously inserted string word that has the prefix prefix, and false otherwise. Input
["Trie", "insert", "search", "search", "startsWith", "insert", "search"]
[[], ["apple"], ["apple"], ["app"], ["app"], ["app"], ["app"]]
Output
[null, null, true, false, true, null, true]
Explanation
1 <= word.length, prefix.length <= 2000word and prefix consist only of lowercase English letters.insert, search, and startsWith.The basic idea of a Trie is to store strings in a tree-like structure where each node represents a single character. Each path down the tree represents a string. We add two special features to our nodes:
We'll implement the basic Trie operations:
Instead of using a fixed size array for the children nodes, we can use a HashMap to dynamically store only the necessary characters. This saves space, especially in cases where the alphabet size is large or the set of possible characters is sparse.