Social feed~55 min2s · 256 MBtarget O(n + L) time, O(26 L) spacestring-algorithms · trie
A feed moderation tool scans posts for banned words. A post is one string of lowercase letters, and the banned words form a list. The same word may be listed twice.
For each banned word, the tool counts how many times it appears in the post. Appearances may overlap, and a word that ends inside another banned word still counts on its own. The tool scans many posts, so it must read each post only once.
Write banned_counts(text, words).
text holds lowercase letters, and its positions start at 0.words[w] is a banned word of lowercase letters. Words may repeat.i where the word appears in text starting at i. Overlapping appearances all count.words.Input: text = "abababa", words = ["aba", "bab", "ab", "ababa", "b"]
Output: [3, 2, 3, 2, 3]The word aba appears at positions 0, 2 and 4. The word bab appears at positions 1 and 3. The word ab appears at positions 0, 2 and 4, and ababa at positions 0 and 2. The word b appears at positions 1, 3 and 5.
The solution builds a trie of the words. Every node gets a fail link to the node of the longest proper ending of its word that is also in the trie. It reads the text once and falls back along fail links when a letter does not fit.
| Node (its word) | a | ab | aba | b | ba | bab | abab | ababa |
|---|---|---|---|---|---|---|---|---|
| Node number | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |
| Fail link | root | b | ba | root | a | ab | bab | aba |
Reading abababa, the walk visits the nodes a, ab, aba, abab and ababa. Then it falls back from ababa to aba, takes b to reach abab, and reaches ababa again. The nodes abab and ababa are each visited twice. Pushing those counts up the fail links gives aba 3 visits, bab 2, ab 3, ababa 2 and b 3.
Input: text = "abc", words = ["x", "cb"]
Output: [0, 0]Neither word appears.
Input: text = "aaaa", words = ["aa", "a"]
Output: [3, 4]The word aa appears at positions 0, 1 and 2, and a appears at all four positions.
1 ≤ text.length ≤ 100,000, and text has only the letters a to z1 ≤ words.length ≤ 5,000, and each word has 1 to 20 letters from a to zScanning the text once for each word costs about words × n steps. That is up to 5,000 × 100,000 = 5 × 10^8, and more when words appear often. The automaton reads the text once and costs about n plus the total length of the words, at most about 2 × 10^5 steps.