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 modulo109 + 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
Problem summary: 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 109 + 7.
Baseline thinking
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Use DP with 4 states (pos: Int, posEvil: Int, equalToS1: Bool, equalToS2: Bool) which compute the number of valid strings of size "pos" where the maximum common suffix with string "evil" has size "posEvil". When "equalToS1" is "true", the current valid string is equal to "S1" otherwise it is greater. In a similar way when equalToS2 is "true" the current valid string is equal to "S2" otherwise it is smaller.
To update the maximum common suffix with string "evil" use KMP preprocessing.
Interview move: turn each hint into an invariant you can check after every iteration/recursion step.
Step 03
Algorithm Walkthrough
Iteration Checklist
Define state (indices, window, stack, map, DP cell, or recursion frame).
Apply one transition step and update the invariant.
Record answer candidate when condition is met.
Continue until all input is consumed.
Use the first example testcase as your mental trace to verify each transition.
Step 04
Edge Cases
Minimum Input
Single element / shortest valid input
Validate boundary behavior before entering the main loop or recursion.
Duplicates & Repeats
Repeated values / repeated states
Decide whether duplicates should be merged, skipped, or counted explicitly.
Extreme Constraints
Largest constraint values
Re-check complexity target against constraints to avoid time-limit issues.
Invalid / Corner Shape
Empty collections, zeros, or disconnected structures
Handle special-case structure before the core algorithm path.
Step 05
Full Annotated Code
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #1397: Find All Good Strings
class Solution {
public int findGoodStrings(int n, String s1, String s2, String evil) {
Integer[][][][] mem = new Integer[n][evil.length()][2][2];
// nextMatchedCount[i][j] := the number of next matched evil count, where
// there're j matches with `evil` and the current letter is ('a' + j)
Integer[][] nextMatchedCount = new Integer[evil.length()][26];
return count(s1, s2, evil, 0, 0, true, true, getLPS(evil), nextMatchedCount, mem);
}
private static final int MOD = 1_000_000_007;
// Returns the number of good strings for s[i..n), where there're j matches
// with `evil`, `isS1Prefix` indicates if the current letter is tightly bound
// for `s1` and `isS2Prefix` indicates if the current letter is tightly bound
// for `s2`.
private int count(final String s1, final String s2, final String evil, int i,
int matchedEvilCount, boolean isS1Prefix, boolean isS2Prefix, int[] evilLPS,
Integer[][] nextMatchedCount, Integer[][][][] mem) {
// s[0..i) contains `evil`, so don't consider any ongoing strings.
if (matchedEvilCount == evil.length())
return 0;
// Run out of strings, so contribute one.
if (i == s1.length())
return 1;
final int k1 = isS1Prefix ? 1 : 0;
final int k2 = isS2Prefix ? 1 : 0;
if (mem[i][matchedEvilCount][k1][k2] != null)
return mem[i][matchedEvilCount][k1][k2];
mem[i][matchedEvilCount][k1][k2] = 0;
final char minChar = isS1Prefix ? s1.charAt(i) : 'a';
final char maxChar = isS2Prefix ? s2.charAt(i) : 'z';
for (char c = minChar; c <= maxChar; ++c) {
final int nextMatchedEvilCount =
getNextMatchedEvilCount(nextMatchedCount, evil, matchedEvilCount, c, evilLPS);
mem[i][matchedEvilCount][k1][k2] +=
count(s1, s2, evil, i + 1, nextMatchedEvilCount, isS1Prefix && c == s1.charAt(i),
isS2Prefix && c == s2.charAt(i), evilLPS, nextMatchedCount, mem);
mem[i][matchedEvilCount][k1][k2] %= MOD;
}
return mem[i][matchedEvilCount][k1][k2];
}
// Returns the lps array, where lps[i] is the length of the longest prefix of
// pattern[0..i] which is also a suffix of this substring.
private int[] getLPS(final String pattern) {
int[] lps = new int[pattern.length()];
for (int i = 1, j = 0; i < pattern.length(); ++i) {
while (j > 0 && pattern.charAt(j) != pattern.charAt(i))
j = lps[j - 1];
if (pattern.charAt(i) == pattern.charAt(j))
lps[i] = ++j;
}
return lps;
}
// j := the next index we're trying to match with `currLetter`
private int getNextMatchedEvilCount(Integer[][] nextMatchedCount, final String evil, int j,
char currChar, int[] lps) {
if (nextMatchedCount[j][currChar - 'a'] != null)
return nextMatchedCount[j][currChar - 'a'];
while (j > 0 && evil.charAt(j) != currChar)
j = lps[j - 1];
return nextMatchedCount[j][currChar - 'a'] = (evil.charAt(j) == currChar ? j + 1 : j);
}
}
// Accepted solution for LeetCode #1397: Find All Good Strings
// Auto-generated Go example from java.
func exampleSolution() {
}
// Reference (java):
// // Accepted solution for LeetCode #1397: Find All Good Strings
// class Solution {
// public int findGoodStrings(int n, String s1, String s2, String evil) {
// Integer[][][][] mem = new Integer[n][evil.length()][2][2];
// // nextMatchedCount[i][j] := the number of next matched evil count, where
// // there're j matches with `evil` and the current letter is ('a' + j)
// Integer[][] nextMatchedCount = new Integer[evil.length()][26];
// return count(s1, s2, evil, 0, 0, true, true, getLPS(evil), nextMatchedCount, mem);
// }
//
// private static final int MOD = 1_000_000_007;
//
// // Returns the number of good strings for s[i..n), where there're j matches
// // with `evil`, `isS1Prefix` indicates if the current letter is tightly bound
// // for `s1` and `isS2Prefix` indicates if the current letter is tightly bound
// // for `s2`.
// private int count(final String s1, final String s2, final String evil, int i,
// int matchedEvilCount, boolean isS1Prefix, boolean isS2Prefix, int[] evilLPS,
// Integer[][] nextMatchedCount, Integer[][][][] mem) {
// // s[0..i) contains `evil`, so don't consider any ongoing strings.
// if (matchedEvilCount == evil.length())
// return 0;
// // Run out of strings, so contribute one.
// if (i == s1.length())
// return 1;
// final int k1 = isS1Prefix ? 1 : 0;
// final int k2 = isS2Prefix ? 1 : 0;
// if (mem[i][matchedEvilCount][k1][k2] != null)
// return mem[i][matchedEvilCount][k1][k2];
// mem[i][matchedEvilCount][k1][k2] = 0;
// final char minChar = isS1Prefix ? s1.charAt(i) : 'a';
// final char maxChar = isS2Prefix ? s2.charAt(i) : 'z';
// for (char c = minChar; c <= maxChar; ++c) {
// final int nextMatchedEvilCount =
// getNextMatchedEvilCount(nextMatchedCount, evil, matchedEvilCount, c, evilLPS);
// mem[i][matchedEvilCount][k1][k2] +=
// count(s1, s2, evil, i + 1, nextMatchedEvilCount, isS1Prefix && c == s1.charAt(i),
// isS2Prefix && c == s2.charAt(i), evilLPS, nextMatchedCount, mem);
// mem[i][matchedEvilCount][k1][k2] %= MOD;
// }
// return mem[i][matchedEvilCount][k1][k2];
// }
//
// // Returns the lps array, where lps[i] is the length of the longest prefix of
// // pattern[0..i] which is also a suffix of this substring.
// private int[] getLPS(final String pattern) {
// int[] lps = new int[pattern.length()];
// for (int i = 1, j = 0; i < pattern.length(); ++i) {
// while (j > 0 && pattern.charAt(j) != pattern.charAt(i))
// j = lps[j - 1];
// if (pattern.charAt(i) == pattern.charAt(j))
// lps[i] = ++j;
// }
// return lps;
// }
//
// // j := the next index we're trying to match with `currLetter`
// private int getNextMatchedEvilCount(Integer[][] nextMatchedCount, final String evil, int j,
// char currChar, int[] lps) {
// if (nextMatchedCount[j][currChar - 'a'] != null)
// return nextMatchedCount[j][currChar - 'a'];
// while (j > 0 && evil.charAt(j) != currChar)
// j = lps[j - 1];
// return nextMatchedCount[j][currChar - 'a'] = (evil.charAt(j) == currChar ? j + 1 : j);
// }
// }
# Accepted solution for LeetCode #1397: Find All Good Strings
class Solution:
def findGoodStrings(self, n: int, s1: str, s2: str, evil: str) -> int:
MOD = 1_000_000_007
evilLPS = self._getLPS(evil)
@functools.lru_cache(None)
def getNextMatchedEvilCount(j: int, currChar: str) -> int:
"""
Returns the number of next matched evil count, where there're j matches
with `evil` and the current letter is ('a' + j).
"""
while j > 0 and evil[j] != currChar:
j = evilLPS[j - 1]
return j + 1 if evil[j] == currChar else j
@functools.lru_cache(None)
def dp(i: int, matchedEvilCount: int, isS1Prefix: bool, isS2Prefix: bool) -> int:
"""
Returns the number of good strings for s[i..n), where there're j matches
with `evil`, `isS1Prefix` indicates if the current letter is tightly bound
for `s1` and `isS2Prefix` indicates if the current letter is tightly bound
for `s2`.
"""
# s[0..i) contains `evil`, so don't consider any ongoing strings.
if matchedEvilCount == len(evil):
return 0
# Run out of strings, so contribute one.
if i == n:
return 1
ans = 0
minCharIndex = ord(s1[i]) if isS1Prefix else ord('a')
maxCharIndex = ord(s2[i]) if isS2Prefix else ord('z')
for charIndex in range(minCharIndex, maxCharIndex + 1):
c = chr(charIndex)
nextMatchedEvilCount = getNextMatchedEvilCount(matchedEvilCount, c)
ans += dp(i + 1, nextMatchedEvilCount,
isS1Prefix and c == s1[i],
isS2Prefix and c == s2[i])
ans %= MOD
return ans
return dp(0, 0, True, True)
def _getLPS(self, pattern: str) -> list[int]:
"""
Returns the lps array, where lps[i] is the length of the longest prefix of
pattern[0..i] which is also a suffix of this substring.
"""
lps = [0] * len(pattern)
j = 0
for i in range(1, len(pattern)):
while j > 0 and pattern[j] != pattern[i]:
j = lps[j - 1]
if pattern[i] == pattern[j]:
lps[i] = j + 1
j += 1
return lps
// Accepted solution for LeetCode #1397: Find All Good Strings
/**
* [1397] Find All Good Strings
*
* 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 == n
* s2.length == n
* s1 <= s2
* 1 <= n <= 500
* 1 <= evil.length <= 50
* All strings consist of lowercase English letters.
*
*/
pub struct Solution {}
// problem: https://leetcode.com/problems/find-all-good-strings/
// discuss: https://leetcode.com/problems/find-all-good-strings/discuss/?currentPage=1&orderBy=most_votes&query=
// submission codes start here
impl Solution {
// Credit: https://leetcode.com/problems/find-all-good-strings/solutions/3107494/just-a-runnable-solution/
pub fn find_good_strings(n: i32, s1: String, s2: String, evil: String) -> i32 {
let mut dp = vec![vec![vec![vec![0; 2]; 2]; evil.len() + 1]; n as usize + 1];
let lps = Self::compute_lps(&evil);
Self::dfs_helper(0, 0, true, true, n, &s1, &s2, &evil, &lps, &mut dp)
}
fn dfs_helper(
i: usize,
evil_matched: usize,
left_bound: bool,
right_bound: bool,
n: i32,
s1: &String,
s2: &String,
evil: &String,
lps: &Vec<usize>,
dp: &mut Vec<Vec<Vec<Vec<i32>>>>,
) -> i32 {
if evil_matched == evil.len() {
return 0;
}
if i == n as usize {
return 1;
}
if dp[i][evil_matched][left_bound as usize][right_bound as usize] != 0 {
return dp[i][evil_matched][left_bound as usize][right_bound as usize];
}
let from = if left_bound { s1.as_bytes()[i] } else { b'a' };
let to = if right_bound { s2.as_bytes()[i] } else { b'z' };
let mut res = 0;
for c in from..=to {
let mut j = evil_matched;
while j > 0 && evil.as_bytes()[j] != c {
j = lps[j - 1];
}
if evil.as_bytes()[j] == c {
j += 1;
}
res += Self::dfs_helper(
i + 1,
j,
left_bound && (c == from),
right_bound && (c == to),
n,
s1,
s2,
evil,
lps,
dp,
);
res %= 1000000007;
}
dp[i][evil_matched][left_bound as usize][right_bound as usize] = res;
res
}
fn compute_lps(str: &String) -> Vec<usize> {
let n = str.len();
let mut lps = vec![0; n];
for i in 1..n {
let mut j = lps[i - 1];
while j > 0 && str.as_bytes()[i] != str.as_bytes()[j] {
j = lps[j - 1];
}
if str.as_bytes()[i] == str.as_bytes()[j] {
lps[i] = j + 1;
}
}
lps
}
}
// submission codes end
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_1397_example_1() {
let n = 2;
let s1 = "aa".to_string();
let s2 = "da".to_string();
let evil = "b".to_string();
let result = 51;
assert_eq!(Solution::find_good_strings(n, s1, s2, evil), result);
}
#[test]
fn test_1397_example_2() {
let n = 8;
let s1 = "leetcode".to_string();
let s2 = "leetgoes".to_string();
let evil = "leet".to_string();
let result = 0;
assert_eq!(Solution::find_good_strings(n, s1, s2, evil), result);
}
#[test]
fn test_1397_example_3() {
let n = 2;
let s1 = "gx".to_string();
let s2 = "gz".to_string();
let evil = "x".to_string();
let result = 2;
assert_eq!(Solution::find_good_strings(n, s1, s2, evil), result);
}
}
// Accepted solution for LeetCode #1397: Find All Good Strings
// Auto-generated TypeScript example from java.
function exampleSolution(): void {
}
// Reference (java):
// // Accepted solution for LeetCode #1397: Find All Good Strings
// class Solution {
// public int findGoodStrings(int n, String s1, String s2, String evil) {
// Integer[][][][] mem = new Integer[n][evil.length()][2][2];
// // nextMatchedCount[i][j] := the number of next matched evil count, where
// // there're j matches with `evil` and the current letter is ('a' + j)
// Integer[][] nextMatchedCount = new Integer[evil.length()][26];
// return count(s1, s2, evil, 0, 0, true, true, getLPS(evil), nextMatchedCount, mem);
// }
//
// private static final int MOD = 1_000_000_007;
//
// // Returns the number of good strings for s[i..n), where there're j matches
// // with `evil`, `isS1Prefix` indicates if the current letter is tightly bound
// // for `s1` and `isS2Prefix` indicates if the current letter is tightly bound
// // for `s2`.
// private int count(final String s1, final String s2, final String evil, int i,
// int matchedEvilCount, boolean isS1Prefix, boolean isS2Prefix, int[] evilLPS,
// Integer[][] nextMatchedCount, Integer[][][][] mem) {
// // s[0..i) contains `evil`, so don't consider any ongoing strings.
// if (matchedEvilCount == evil.length())
// return 0;
// // Run out of strings, so contribute one.
// if (i == s1.length())
// return 1;
// final int k1 = isS1Prefix ? 1 : 0;
// final int k2 = isS2Prefix ? 1 : 0;
// if (mem[i][matchedEvilCount][k1][k2] != null)
// return mem[i][matchedEvilCount][k1][k2];
// mem[i][matchedEvilCount][k1][k2] = 0;
// final char minChar = isS1Prefix ? s1.charAt(i) : 'a';
// final char maxChar = isS2Prefix ? s2.charAt(i) : 'z';
// for (char c = minChar; c <= maxChar; ++c) {
// final int nextMatchedEvilCount =
// getNextMatchedEvilCount(nextMatchedCount, evil, matchedEvilCount, c, evilLPS);
// mem[i][matchedEvilCount][k1][k2] +=
// count(s1, s2, evil, i + 1, nextMatchedEvilCount, isS1Prefix && c == s1.charAt(i),
// isS2Prefix && c == s2.charAt(i), evilLPS, nextMatchedCount, mem);
// mem[i][matchedEvilCount][k1][k2] %= MOD;
// }
// return mem[i][matchedEvilCount][k1][k2];
// }
//
// // Returns the lps array, where lps[i] is the length of the longest prefix of
// // pattern[0..i] which is also a suffix of this substring.
// private int[] getLPS(final String pattern) {
// int[] lps = new int[pattern.length()];
// for (int i = 1, j = 0; i < pattern.length(); ++i) {
// while (j > 0 && pattern.charAt(j) != pattern.charAt(i))
// j = lps[j - 1];
// if (pattern.charAt(i) == pattern.charAt(j))
// lps[i] = ++j;
// }
// return lps;
// }
//
// // j := the next index we're trying to match with `currLetter`
// private int getNextMatchedEvilCount(Integer[][] nextMatchedCount, final String evil, int j,
// char currChar, int[] lps) {
// if (nextMatchedCount[j][currChar - 'a'] != null)
// return nextMatchedCount[j][currChar - 'a'];
// while (j > 0 && evil.charAt(j) != currChar)
// j = lps[j - 1];
// return nextMatchedCount[j][currChar - 'a'] = (evil.charAt(j) == currChar ? j + 1 : j);
// }
// }
Step 06
Interactive Study Demo
Use this to step through a reusable interview workflow for this problem.
Press Step or Run All to begin.
Step 07
Complexity Analysis
Time
O(n × m)
Space
O(n × m)
Approach Breakdown
RECURSIVE
O(2ⁿ) time
O(n) space
Pure recursion explores every possible choice at each step. With two choices per state (take or skip), the decision tree has 2ⁿ leaves. The recursion stack uses O(n) space. Many subproblems are recomputed exponentially many times.
DYNAMIC PROGRAMMING
O(n × m) time
O(n × m) space
Each cell in the DP table is computed exactly once from previously solved subproblems. The table dimensions determine both time and space. Look for the state variables — each unique combination of state values is one cell. Often a rolling array can reduce space by one dimension.
Shortcut: Count your DP state dimensions → that’s your time. Can you drop one? That’s your space optimization.
Coach Notes
Common Mistakes
Review these before coding to avoid predictable interview regressions.
State misses one required dimension
Wrong move: An incomplete state merges distinct subproblems and caches incorrect answers.
Usually fails on: Correctness breaks on cases that differ only in hidden state.
Fix: Define state so each unique subproblem maps to one DP cell.