Implement Trie (Prefix Tree)
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 very efficient 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.
Examples
Constraints
1 <= word.length, prefix.length <= 2000word and prefix consist only of lowercase English letters.At most 3 * 10^4 calls in total will be made to insert, search, and startsWith.
Hash Map (or Array) Node
Approach
Create a `TrieNode` class. Each node has a hash map (or an array of size 26) representing its children, and a boolean flag `isEndOfWord`. For `insert`, iterate through the characters of the word. If a character is not in the current node's children, add a new `TrieNode`. Then move to the child node. Finally, set `isEndOfWord = true` at the last node. `search` and `startsWith` follow a similar traversal pattern. If a character is missing, return `false`. For `search`, check the `isEndOfWord` flag at the end, while `startsWith` just returns `true` if the traversal finishes successfully.
Complexity Analysis
Where m is the length of the word/prefix and N is the number of inserted words.
class TrieNode { TrieNode[] children; boolean isEndOfWord; public TrieNode() { children = new TrieNode[26]; isEndOfWord = false; }}
class Trie { private TrieNode root;
public Trie() { root = new TrieNode(); } public void insert(String word) { TrieNode curr = root; for (char c : word.toCharArray()) { int index = c - 'a'; if (curr.children[index] == null) { curr.children[index] = new TrieNode(); } curr = curr.children[index]; } curr.isEndOfWord = true; } public boolean search(String word) { TrieNode curr = root; for (char c : word.toCharArray()) { int index = c - 'a'; if (curr.children[index] == null) { return false; } curr = curr.children[index]; } return curr.isEndOfWord; } public boolean startsWith(String prefix) { TrieNode curr = root; for (char c : prefix.toCharArray()) { int index = c - 'a'; if (curr.children[index] == null) { return false; } curr = curr.children[index]; } return true; }}