Find All Good Strings Problem
Description
LeetCode Problem 1397.
Given the strings s1 and s2 of size n and the string evil, return the number of good strings.
A good string has size n, it is alphabetically greater than or equal to s1, it is alphabetically smaller than or equal to s2, and it does not contain the string evil as a substring. Since the answer can be a huge number, return this modulo 10^9 + 7.
Example 1:
Input: n = 2, s1 = "aa", s2 = "da", evil = "b"
Output: 51
Explanation: There are 25 good strings starting with 'a': "aa","ac","ad",...,"az". Then there are 25 good strings starting with 'c': "ca","cc","cd",...,"cz" and finally there is one good string starting with 'd': "da".
Example 2:
Input: n = 8, s1 = "leetcode", s2 = "leetgoes", evil = "leet"
Output: 0
Explanation: All strings greater than or equal to s1 and smaller than or equal to s2 start with the prefix "leet", therefore, there is not any good string.
Example 3:
Input: n = 2, s1 = "gx", s2 = "gz", evil = "x"
Output: 2
Constraints:
s1.length == ns2.length == ns1 <= s21 <= n <= 5001 <= evil.length <= 50- All strings consist of lowercase English letters.
Solution
Approach: Digit DP with a KMP Automaton
We build the string one letter at a time from the left and count, with dynamic programming, how many prefixes can still become a good string. A prefix needs three pieces of information:
- How much of
evilit currently ends with. Letjbe the length of the longest suffix of the prefix that is also a prefix ofevil. Ifjever reacheslen(evil),evilhas appeared and the prefix is dead. - Whether it still equals
s1's prefix. If so, the next letter may not be smaller than the next letter ofs1; once we pick a larger letter the lower bound no longer matters. - Whether it still equals
s2's prefix, which limits the next letter from above in the same way.
So the state is dp[j][tight], where tight is two bits: bit 1 for "still on s1", bit 2 for "still on s2". We start with the empty prefix, dp[0][3] = 1, since it matches both bounds.
To update j when a letter c is appended we use the KMP automaton of evil. First compute the failure function fail (the longest proper border of each prefix of evil), then the table step[j][c]: if evil[j] == c the match grows to j + 1; otherwise fall back to step[fail[j - 1]][c], or 0 when j == 0. A plain "reset to 0 on a mismatch" would be wrong: with evil = "aab" and prefix "aa", appending another a must keep j = 2 (the prefix ends in "aa"), not drop to 0.
For each position i, every state tries each allowed letter c: from s1[i] (if bit 1 is set, otherwise 'a') to s2[i] (if bit 2 is set, otherwise 'z'). It skips letters with step[j][c] == len(evil), keeps bit 1 only if c == s1[i] and bit 2 only if c == s2[i], and adds its count to the new state modulo 109 + 7. After n letters, the answer is the sum over all states.
Handling both bounds in one pass avoids the usual "count up to s2, subtract the count below s1" bookkeeping, which needs a separate check for s1 itself.
Complexity: O(n * m * 26) time for the DP plus O(m * 26) for the automaton, where m is the length of evil (the four tight values are a constant factor), and O(m * 26) space.
class Solution:
def findGoodStrings(self, n: int, s1: str, s2: str, evil: str) -> int:
MOD = 10**9 + 7
m = len(evil)
# KMP failure function: fail[i] = longest proper border of evil[:i + 1]
fail = [0] * m
k = 0
for i in range(1, m):
while k > 0 and evil[i] != evil[k]:
k = fail[k - 1]
if evil[i] == evil[k]:
k += 1
fail[i] = k
# step[j][c] = letters of evil matched after appending letter c to a string that matched j
step = [[0] * 26 for _ in range(m)]
for j in range(m):
for c in range(26):
if ord(evil[j]) - 97 == c:
step[j][c] = j + 1
elif j > 0:
step[j][c] = step[fail[j - 1]][c]
# dp[j][tight]: prefixes so far that match j letters of evil; tight bit 1 = prefix equals
# s1's prefix (lower bound still active), bit 2 = prefix equals s2's (upper bound still active)
dp = [[0] * 4 for _ in range(m)]
dp[0][3] = 1
for i in range(n):
lo, hi = ord(s1[i]) - 97, ord(s2[i]) - 97
new = [[0] * 4 for _ in range(m)]
for j in range(m):
for tight in range(4):
ways = dp[j][tight]
if ways == 0:
continue
first = lo if tight & 1 else 0
last = hi if tight & 2 else 25
for c in range(first, last + 1):
nj = step[j][c]
if nj == m:
continue # evil would end here
nt = (tight & 1 if c == lo else 0) | (tight & 2 if c == hi else 0)
new[nj][nt] = (new[nj][nt] + ways) % MOD
dp = new
return sum(map(sum, dp)) % MOD