Find All Good Strings - Problem
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⁹ + 7.
Input & Output
Example 1 — Basic Case
$
Input:
n = 2, s1 = "aa", s2 = "da", evil = "b"
›
Output:
51
💡 Note:
Valid strings are from "aa" to "da" without containing "b": aa, ac, ad, ..., ca, cc, cd, da. Count excludes any string with 'b'.
Example 2 — Evil Substring Blocking
$
Input:
n = 8, s1 = "leetcode", s2 = "leetgoes", evil = "leet"
›
Output:
0
💡 Note:
Since s1 starts with "leet" and evil is "leet", any valid string would contain the evil substring, so result is 0.
Example 3 — No Evil Match
$
Input:
n = 2, s1 = "gx", s2 = "gz", evil = "x"
›
Output:
2
💡 Note:
Valid strings in range [gx, gz] without 'x' are: gy, gz. Total count is 2.
Constraints
- 1 ≤ n ≤ 500
- 1 ≤ |evil| ≤ 50
- s1.length == s2.length == n
- s1 ≤ s2
- s1, s2, evil consist only of lowercase letters
Visualization
Tap to expand
Understanding the Visualization
1
Input
Range [s1, s2], length n, forbidden evil string
2
Process
Generate valid strings avoiding evil substring
3
Output
Count of good strings modulo 10^9+7
Key Takeaway
🎯 Key Insight: Use KMP failure function to efficiently track partial matches of the evil substring while building valid strings with dynamic programming.
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code