Question 40: Implement Trie (Prefix Tree)
Question (from PDF): Implement a Trie data structure to support insert, search, and startsWith
operations efficiently. Each node should represent a character from a lowercase English word.
Problem: Implement a Trie with insert, search, and startsWith operations.
Algorithm: - Use a tree of TrieNodes with 26 children.
Time Complexity: O(n) per operation
Space Complexity: O(n * k) for inserted words
Java Code:
class TrieNode {
TrieNode[] children = new TrieNode[26];
boolean isEndOfWord;
}
public class Trie {
private TrieNode root;
public Trie() {
root = new TrieNode();
}
public void insert(String word) {
TrieNode node = root;
for (char c : word.toCharArray()) {
int index = c - 'a';
if (node.children[index] == null)
node.children[index] = new TrieNode();
node = node.children[index];
}
node.isEndOfWord = true;
}
public boolean search(String word) {
TrieNode node = root;
for (char c : word.toCharArray()) {
int index = c - 'a';
if (node.children[index] == null) return false;
node = node.children[index];
}
return node.isEndOfWord;
}
public boolean startsWith(String prefix) {
TrieNode node = root;
1
for (char c : prefix.toCharArray()) {
int index = c - 'a';
if (node.children[index] == null) return false;
node = node.children[index];
}
return true;
}
}