Implement Trie II (Prefix Tree)
Pattern: Insert, search and prefix
Each node counts the words passing through it and the words ending there. Inserting adds 1 along the path, erasing subtracts 1, and the two count queries read the counters at the end of a walk.
The problem
Implement Trie with insert(word), countWordsEqualTo(word), countWordsStartingWith(prefix) and erase(word) (the word is always present when erased). The same word may be inserted many times.
Think first
- What does a flag lose when a word is inserted twice?
- Which counter answers the prefix question?
- What does erase change?
Hints
Brute force, and why it fails
Keep a list of words and scan it per query.
The key insight
Counts on the nodes turn every question into one walk.
Dry run
insert apple twice: every node on the path has pass 2; the e node has end 2.
Step 1 of 3
The plan
insert: walk, pass += 1 on each node, end += 1 at the last
erase: the same with -1
count equal: end at the last node; count prefix: pass at the last node
Complexity
- Time
O(L) per call- Space
O(total letters)
One walk per call.
Edge cases
- Counting a prefix that is not there: 0.
- Erasing the only copy.
- Repeated inserts.
I've built my logic, show the code
Java
class Trie {
private static class Node {
Node[] next = new Node[26];
int pass; // how many words pass through (or end at) this node
int end; // how many words end exactly 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();
n = n.next[c - 'a'];
n.pass++;
}
n.end++;
}
public int countWordsEqualTo(String word) {
Node n = walk(word);
return n == null ? 0 : n.end;
}
public int countWordsStartingWith(String prefix) {
Node n = walk(prefix);
return n == null ? 0 : n.pass; // every word through this node has the prefix
}
public void erase(String word) { // the word is known to be present
Node n = root;
for (char c : word.toCharArray()) {
n = n.next[c - 'a'];
n.pass--; // one word fewer passes each node on its path
}
n.end--;
}
private Node walk(String s) {
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], 0 = none
vector<int> pass{0}, ends{0}; // words through each node / words ending at it
void insert(string word) {
int n = 0;
for (char c : word) {
if (next[n][c - 'a'] == 0) {
next[n][c - 'a'] = static_cast<int>(next.size());
next.push_back(vector<int>(26, 0));
pass.push_back(0);
ends.push_back(0);
}
n = next[n][c - 'a'];
pass[n]++;
}
ends[n]++;
}
int countWordsEqualTo(string word) {
int n = walk(word);
return n == -1 ? 0 : ends[n];
}
int countWordsStartingWith(string prefix) {
int n = walk(prefix);
return n == -1 ? 0 : pass[n]; // every word through this node has the prefix
}
void erase(string word) { // the word is known to be present
int n = 0;
for (char c : word) {
n = next[n][c - 'a'];
pass[n]--; // one word fewer passes each node on its path
}
ends[n]--;
}
int walk(const string& s) {
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 = {"pass": 0, "end": 0} # letters map to children; pass and end are counts
def insert(self, word: str) -> None:
node = self.root
for c in word:
node = node.setdefault(c, {"pass": 0, "end": 0})
node["pass"] += 1 # one more word passes through
node["end"] += 1
def countWordsEqualTo(self, word: str) -> int:
node = self._walk(word)
return node["end"] if node else 0
def countWordsStartingWith(self, prefix: str) -> int:
node = self._walk(prefix)
return node["pass"] if node else 0 # every word through this node has the prefix
def erase(self, word: str) -> None: # the word is known to be present
node = self.root
for c in word:
node = node[c]
node["pass"] -= 1
node["end"] -= 1
def _walk(self, s):
node = self.root
for c in s:
if c not in node:
return None
node = node[c]
return nodeCommon mistakes
- Removing nodes on erase (not needed).
- Forgetting the root is not counted.