Online store~30 min2s · 256 MBtarget O(L × min(26^d, N × L)) time, O(N × L × 26) spaceclassic twin: lc-211trie
A shop's search box suggests words as people type. The merchandising team keeps a book of suggestion words, adds new ones and drops old ones during the day.
An editor tests the book with patterns. A pattern is made of letters and dots, and a dot stands for any one letter. For each test, the editor wants to know how many words in the book fit the pattern right now.
Write run_word_book(commands, words).
commands[i] is "add", "drop" or "count", and words[i] is its word. Run them in order, starting with an empty book.add puts a word of lowercase letters into the book. If it is already there, nothing changes.drop takes a word of lowercase letters out of the book. If it is not there, nothing changes.count carries a pattern of lowercase letters and dots. It fits a word when both have the same length, and every letter of the pattern equals the letter of the word at its place. A dot fits any letter.count command, in order: the number of words in the book that fit the pattern.Input: commands = ["add", "add", "add", "add", "count", "count", "count", "drop", "count"], words = ["cat", "car", "cap", "dog", "ca.", "...", "c..", "car", "ca."]
Output: [3, 4, 3, 2]After four adds the book holds cat, car, cap and dog. The pattern ca. follows c, then a, then every child of that node: t, r and p.
| Command | What happens | Answer |
|---|---|---|
count ca. |
letters c, a, then three children where a word ends |
3 |
count ... |
three levels of dots reach all four words | 4 |
count c.. |
c, then every child, then every child: cat, car, cap |
3 |
drop car |
the flag of the node car is cleared |
|
count ca. |
the node car no longer ends a word |
2 |
Input: commands = ["add", "add", "count", "count"], words = ["bad", "bade", "ba", "ba.."]
Output: [0, 1]The pattern ba is a prefix of both words, but it must fit a whole word, and no word has two letters. The pattern ba.. fits bade.
Input: commands = ["add", "add", "count", "drop", "count"], words = ["bad", "bad", "...", "bad", "..."]
Output: [1, 0]Adding bad twice stores one word, so one drop empties the book.
1 ≤ len(commands) = len(words) ≤ 6,000add, drop or countadd or drop has 1 to 10 lowercase letters, and a pattern has 1 to 10 letters or dotsChecking every word of the book against a pattern costs about 3,000 words × 10 letters = 30,000 steps. With 3,000 questions that is 90 million steps, which is too slow in some languages.
A trie follows a letter in one step. A dot branches, but only into the children that exist, so most patterns touch a small part of the book.