Tries Prefix trees
425. Implement Trie II (Prefix Tree)
This trie keeps a count for every word, so the same word can be added more than once. Write a class Trie
with four methods:
insert(word)adds one copy ofword.countWordsEqualTo(word)returns how many copies ofwordthe trie holds.countWordsStartingWith(prefix)returns how many words in the trie start withprefix, counting every copy.erase(word)removes one copy ofword. It is only called when the trie holds at least one copy.
A word starts with itself, so after insert("plan") twice, countWordsStartingWith("plan") is 2. Each
method must run in O(L) time, where L is the length of its argument, however many words the trie holds.
Your class is tested by replaying a list of calls on a new, empty Trie. ops[i] names the i-th call:
"insert", "countWordsEqualTo", "countWordsStartingWith" or "erase", and words[i] is the word or
prefix it is called with. The answer is the list of every value that the two count methods return, in the
order they are called.
In C# and Go the methods are Insert, CountWordsEqualTo, CountWordsStartingWith and Erase, and in
Rust they are insert, count_words_equal_to, count_words_starting_with and erase. Go creates the trie
with Constructor(), and Rust with Trie::new(). The names in ops are the same in every language.
Example 1
Input: ops = ["insert",
"insert",
"insert",
"countWordsEqualTo",
"countWordsStartingWith",
"erase",
"countWordsEqualTo",
"countWordsStartingWith"]
words = ["plan",
"plant",
"plan",
"plan",
"pla",
"plan",
"plan",
"plan"]
[2,3,1,2]Explanation: "plan" is added twice, so there are two copies of it, and all three words start with "pla". After one
copy of "plan" is erased, "plan" and "plant" both start with "plan".
Example 2
Input: ops = ["insert",
"countWordsStartingWith",
"erase",
"countWordsEqualTo",
"countWordsStartingWith",
"insert",
"countWordsStartingWith",
"countWordsEqualTo"]
words = ["go",
"g",
"go",
"go",
"g",
"gone",
"go",
"go"]
[1,0,0,1,0]Explanation: Erasing the only copy of "go" leaves the trie empty, so both counts are 0. "gone" starts with
"go", but no copy of "go" itself is left.
Example 3
Input: ops = ["insert",
"insert",
"insert",
"countWordsStartingWith",
"countWordsStartingWith",
"countWordsEqualTo",
"countWordsStartingWith"]
words = ["sun",
"sunny",
"sun",
"sunn",
"s",
"su",
"suns"]
[1,3,0,0]Explanation: Only "sunny" starts with "sunn". "su" is a prefix of words in the trie but was never added, and no
word starts with "suns".
Check your understanding
Work out the answer for this input before you write any code.
Constraints
1 ≤ ops.length ≤ 105- Each
ops[i]is"insert","countWordsEqualTo","countWordsStartingWith"or"erase". words.lengthequalsops.length.1 ≤ words[i].length ≤ 100- The words in
wordshave at most 106 letters in all. - Each
words[i]is made of lowercase English letters. erase(word)is only called when the trie holds at least one copy ofword.
Clarifying questions
What you would ask an interviewer before writing any code.