Problem
Implement a trie with insert, search and startsWith for lowercase words. search is true only for a complete word, while startsWith is true for any stored word that has that prefix.
Original: LeetCode 208: Implement Trie (Prefix Tree).
Examples
Example 1
`Trie: insert("apple"), search("apple"), search("app"), startsWith("app"), insert("app"), search("app")``[null, true, false, true, null, true]`Constraints
1 <= word.length, prefix.length <= 2000wordandprefixconsist only of lowercase English letters.- At most
3 * 10^4calls in total will be made toinsert,search, andstartsWith.
Hints
Hint 1
A word can be a prefix of another word, so a node may both end a word and have children.
Hint 2
This is the standard prefix tree: an array or map of children plus a boolean end mark.
Solution
Tried it yourself? The approach, complexity, and code stay hidden until you choose.
Approach
Brute force. A hash set of words can implement search, but startsWith then scans every word.
Optimal. 26-wide child arrays for lowercase English, or a HashMap if the alphabet is larger.
Alternative. A compressed trie (radix tree) saves space on unique suffixes, but it is more code than this problem needs.
Complexity
- Time
- O(L)
insert, search and startsWith are O(L) in the length of the argument. Space is O(total characters inserted).
- Space
- O(total characters inserted)
Code
class Trie:
def __init__(self) -> None:
self.root: dict = {}
def insert(self, word: str) -> None:
node = self.root
for ch in word:
node = node.setdefault(ch, {})
node["#"] = True
def _walk(self, s: str):
node = self.root
for ch in s:
if ch not in node:
return None
node = node[ch]
return node
def search(self, word: str) -> bool:
node = self._walk(word)
return bool(node and node.get("#"))
def starts_with(self, prefix: str) -> bool:
return self._walk(prefix) is not None
if __name__ == "__main__":
t = Trie()
t.insert("apple")
assert t.search("apple") is True
assert t.search("app") is False
assert t.starts_with("app") is True
t.insert("app")
assert t.search("app") is True
print("ok")public class ImplementTriePrefixTree {
private static class Node {
final Node[] next = new Node[26];
boolean end;
}
private final Node root = new Node();
void insert(String word) {
var cur = root;
for (int i = 0; i < word.length(); i++) {
int c = word.charAt(i) - 'a';
if (cur.next[c] == null) cur.next[c] = new Node();
cur = cur.next[c];
}
cur.end = true;
}
boolean search(String word) {
var node = walk(word);
return node != null && node.end;
}
boolean startsWith(String prefix) {
return walk(prefix) != null;
}
private Node walk(String s) {
var cur = root;
for (int i = 0; i < s.length(); i++) {
int c = s.charAt(i) - 'a';
if (cur.next[c] == null) return null;
cur = cur.next[c];
}
return cur;
}
public static void main(String[] args) {
var t = new ImplementTriePrefixTree();
t.insert("apple");
if (!t.search("apple") || t.search("app") || !t.startsWith("app")) throw new AssertionError();
t.insert("app");
if (!t.search("app")) throw new AssertionError();
System.out.println("ok");
}
}Edge cases
- Official sample: insert "apple", search "apple" is true, search "app" is false, startsWith "app" is true, then insert "app" and search "app" becomes true.
- An empty prefix matches the root and should return true once the trie exists.
Follow-ups
- Design Add and Search Words adds a '.' wildcard, which turns search into a DFS of the remaining pattern.
Interview script
"Each node has children for the next character and a flag for a word ending. search has to finish on a marked node; startsWith only has to follow the path."
Sources (1)
- LeetCode 208: Implement Trie (Prefix Tree)leetcode.com