Search~30 min2s · 256 MBtarget O(26 × n + total length of terms) time, O(26 × number of terms) spaceclassic twin: lc-438, lc-49window-counts · hashing · sliding-window-fixed
A search engine screens product descriptions before they enter the search index. Some sellers hide a blocked term by scrambling its letters, so "fake" becomes "efak". Before the check, the system removes spaces and punctuation and turns every letter into lowercase.
The trust team keeps a list of blocked terms, all of the same length. A spot is a position in the cleaned description where that many letters in a row are a rearrangement of any blocked term. The team counts the spots in each description. A high count sends the listing to a person for review.
Write count_spots(text, terms).
text is the cleaned description. Only lowercase letters a to z appear in it.terms is the list of blocked terms. Every term has the same length m, uses only lowercase letters a to z, and the list may repeat a term.i is a spot when the m letters of text starting at i are a rearrangement of at least one term. A rearrangement has the same letters, each the same number of times, in any order.text, return 0.Input: text = "efakecopy", terms = ["fake", "copy"]
Output: 3The blocked keys are a1 e1 f1 k1 for "fake" and c1 o1 p1 y1 for "copy". Each window holds m = 4 letters.
| right | Joins | Leaves | Window (start) | Letter counts | A blocked key? | Spots |
|---|---|---|---|---|---|---|
| 0 to 2 | e, f, a | none | not full yet | a1 e1 f1 | no | 0 |
| 3 | k | none | efak (0) | a1 e1 f1 k1 | yes, fake | 1 |
| 4 | e | e | fake (1) | a1 e1 f1 k1 | yes, fake | 2 |
| 5 | c | f | akec (2) | a1 c1 e1 k1 | no | 2 |
| 6 | o | a | keco (3) | c1 e1 k1 o1 | no | 2 |
| 7 | p | k | ecop (4) | c1 e1 o1 p1 | no | 2 |
| 8 | y | e | copy (5) | c1 o1 p1 y1 | yes, copy | 3 |
The spots at positions 0 and 1 overlap, and both count.
Input: text = "tseb", terms = ["best", "bets"]
Output: 1Both terms match position 0, but a position counts once.
Input: text = "ab", terms = ["abc"]
Output: 0The terms are longer than the text, so no position can hold one.
1 ≤ text.length ≤ 10^51 ≤ terms.length ≤ 10001 ≤ terms[i].length ≤ 100, and every term has the same lengtha to z appear in text and in terms.Comparing every position with every term is about 10^5 × 1000 = 10^8 comparisons, and each one sorts up to 100 letters. That is far over the time limit. Aim for about 26 steps per position.
Read the alphabet too. With only 26 letters, the letters of any window fit in an array of 26 counts. Two strings are rearrangements of each other exactly when their 26 counts are equal.