This problem requires implementing a Trie data structure with additional functionalities to count words and prefixes, and to erase words. The solution uses a node-based approach where each node represents a character in a word.
Each node in the Trie consists of:
children
: An array (or map) to store pointers to child nodes. The size of the array depends on the character set (26 for lowercase English letters). children[i]
points to the node representing the (i+1)-th character in the alphabet.v
: An integer representing the number of words ending at this node.pv
: An integer representing the number of words having this node as a prefix.insert(word)
:
word
.children
array.pv
for each node visited along the path.v
for the final node to indicate a complete word.countWordsEqualTo(word)
:
word
.word
, return the v
value of the final node (number of times this exact word exists).countWordsStartingWith(prefix)
:
countWordsEqualTo
, but instead of checking the v
value at the end, return the pv
value of the last node reached in the prefix traversal. This represents all words starting with this prefix.erase(word)
:
word
.pv
for each node visited.v
for the final node.Time Complexity:
insert
, countWordsEqualTo
, countWordsStartingWith
, erase
: O(L), where L is the length of the word or prefix. This is because the operations involve traversing at most L nodes in the Trie.Space Complexity:
The code examples in the provided markdown demonstrate the implementation of the Trie with the above operations. They are well-structured and follow the algorithm explained above. The key is using the children
array, v
, and pv
effectively to track word counts and prefixes. The search function is a helper function to efficiently navigate the Trie during operations.