Implement a trie with insert, search, and startsWith methods.
insert("apple"), search("apple")→true, search("app")→false, startsWith("app")→true
Build a Trie with TrieNode containing children[26] and isEnd flag.
- TrieNode: children[26], boolean isEnd.
- insert: traverse/create nodes char by char, mark last as isEnd.
- search: traverse nodes; return true only if last node has isEnd=true.
- startsWith: traverse nodes; return true if all chars found.
class Trie {
private TrieNode root = new TrieNode();
public void insert(String word) {
TrieNode node = root;
for (char c : word.toCharArray()) {
if (node.children[c-'a'] == null) node.children[c-'a'] = new TrieNode();
node = node.children[c-'a'];
}
node.isEnd = true;
}
public boolean search(String word) {
TrieNode node = root;
for (char c : word.toCharArray()) {
if (node.children[c-'a'] == null) return false;
node = node.children[c-'a'];
}
return node.isEnd;
}
public boolean startsWith(String prefix) {
TrieNode node = root;
for (char c : prefix.toCharArray()) {
if (node.children[c-'a'] == null) return false;
node = node.children[c-'a'];
}
return true;
}
private static class TrieNode {
TrieNode[] children = new TrieNode[26];
boolean isEnd;
}
}
- Time Complexity: insert/search/startsWith: O(L) where L=word length
- Space Complexity: O(N*L) total nodes