Find All Good Strings - Problem
You're tasked with finding "good strings" that satisfy multiple strict criteria. Given three strings - s1, s2 (both of length n), and evil - you need to count all strings of length n that are:
- Lexicographically โฅ s1 (comes at or after s1 in dictionary order)
- Lexicographically โค s2 (comes at or before s2 in dictionary order)
- Does NOT contain
evilas a substring
For example, if s1 = "aa", s2 = "da", and evil = "b", then valid strings include "aa", "ac", "ca", etc., but NOT "ab" (contains evil) or "ea" (> s2).
Return the count modulo 109 + 7 since the answer can be enormous.
Input & Output
example_1.py โ Basic Case
$
Input:
n = 2, s1 = "aa", s2 = "da", evil = "b"
โบ
Output:
51
๐ก Note:
All strings from 'aa' to 'da' that don't contain 'b'. This includes 'aa', 'ac', 'ad', ..., 'ca', 'cc', 'cd', ..., 'da' but excludes any string with 'b' like 'ab', 'ba', 'bb', etc.
example_2.py โ Evil at Start
$
Input:
n = 8, s1 = "leetcode", s2 = "leetgoes", evil = "leet"
โบ
Output:
0
๐ก Note:
Since both s1 and s2 start with 'leet' (which is the evil string), any valid string in the range must also start with 'leet', making it impossible to avoid the evil substring.
example_3.py โ Single Character Range
$
Input:
n = 2, s1 = "gx", s2 = "gz", evil = "x"
โบ
Output:
2
๐ก Note:
Valid strings are 'gy' and 'gz'. 'gx' is excluded because it contains the evil character 'x'.
Visualization
Tap to expand
Understanding the Visualization
1
Setup KMP Automaton
Create a state machine that tracks how close we are to forming the forbidden pattern
2
Dynamic Programming
Build strings position by position, maintaining bounds and pattern state
3
Pruning
Skip any path that would complete the forbidden pattern
4
Count Valid Strings
Sum up all successful paths that reach the end without violations
Key Takeaway
๐ฏ Key Insight: By combining digit DP for lexicographic constraints with KMP automaton for pattern avoidance, we can efficiently explore only valid string constructions without generating invalid paths.
Time & Space Complexity
Time Complexity
O(n ร m ร 8)
n positions, m KMP states, 8 combinations of tight bounds, constant work per state
โ Linear Growth
Space Complexity
O(n ร m ร 8)
Memoization table with dimensions for position, KMP state, and tight flags
โก Linearithmic Space
Constraints
- 1 โค n โค 500
- 1 โค evil.length โค 50
- s1.length == s2.length == n
- s1 โค s2 lexicographically
- s1, s2, and evil consist of lowercase English letters only
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code