Implement Trie (Prefix Tree)
Pattern: Insert, search and prefix
Build a trie: each node has a child per letter and a flag marking where a word ends. Insert walks the word creating nodes; search walks it and checks the flag; startsWith only needs the walk to succeed.
Solve on LeetCodeSolve on GeeksforGeeks
The problem
Implement a class Trie with insert(word), search(word) (was this exact word inserted?) and startsWith(prefix) (was any inserted word starting with it?). Words use lowercase letters. The tests print each call's result in a list, with null for insert and for the constructor.
Think first
- What does one node need?
- How do search and startsWith differ?
- What does an insert cost?
Hints
Brute force, and why it fails
Store words in a list and scan it: O(number of words × length) per query.
The key insight
Words that share a prefix share a path, so every operation costs only the length of its argument.
Dry run
insert apple: the path a, p, p, l, e is created and the e node is marked.
The plan
insert: walk, creating children; mark end
search: walk; true if it finishes at a marked node
startsWith: walk; true if it finishes
Complexity
- Time
O(L) per call- Space
O(total letters)
L is the length of the argument.
Edge cases
- Searching before any insert.
- A word that is a prefix of another.
- Inserting a word twice.
I've built my logic, show the code
Java
class Trie {
private static class Node {
Node[] next = new Node[26]; // one child per letter
boolean end; // a word ends here
}
private final Node root = new Node();
public void insert(String word) {
Node n = root;
for (char c : word.toCharArray()) {
if (n.next[c - 'a'] == null) n.next[c - 'a'] = new Node(); // make the path as needed
n = n.next[c - 'a'];
}
n.end = true;
}
public boolean search(String word) {
Node n = walk(word);
return n != null && n.end; // the path exists and a word ends exactly there
}
public boolean startsWith(String prefix) {
return walk(prefix) != null; // the path exists: some word continues it
}
private Node walk(String s) { // follow s from the root; null if the path breaks
Node n = root;
for (char c : s.toCharArray()) {
n = n.next[c - 'a'];
if (n == null) return null;
}
return n;
}
}C++
class Trie {
public:
vector<vector<int>> next{vector<int>(26, 0)}; // next[node][letter]: child node, 0 = none (node 0 is the root)
vector<bool> end{false}; // end[node]: a word ends here
void insert(string word) {
int n = 0;
for (char c : word) {
if (next[n][c - 'a'] == 0) { // make the path as needed
next[n][c - 'a'] = static_cast<int>(next.size());
next.push_back(vector<int>(26, 0));
end.push_back(false);
}
n = next[n][c - 'a'];
}
end[n] = true;
}
bool search(string word) {
int n = walk(word);
return n != -1 && end[n]; // the path exists and a word ends exactly there
}
bool startsWith(string prefix) {
return walk(prefix) != -1; // the path exists: some word continues it
}
int walk(const string& s) { // follow s from the root; -1 if the path breaks
int n = 0;
for (char c : s) {
n = next[n][c - 'a'];
if (n == 0) return -1;
}
return n;
}
};Python
class Trie:
def __init__(self):
self.root = {} # each node maps a letter to its child; "end" marks a word's end
def insert(self, word: str) -> None:
node = self.root
for c in word:
node = node.setdefault(c, {}) # make the path as needed
node["end"] = True
def search(self, word: str) -> bool:
node = self._walk(word)
return node is not None and "end" in node # the path exists and a word ends exactly there
def startsWith(self, prefix: str) -> bool:
return self._walk(prefix) is not None # the path exists: some word continues it
def _walk(self, s): # follow s from the root; None if the path breaks
node = self.root
for c in s:
if c not in node:
return None
node = node[c]
return nodeCommon mistakes
- Returning true for a prefix in search.
- Creating nodes during search.