Number of Strings Which Can Be Rearranged to Contain Substring Problem
Description
LeetCode Problem 2930.
You are given an integer n.
A string s is called good if it contains only lowercase English characters and it is possible to rearrange the characters of s such that the new string contains "leet" as a substring.
For example:
- The string
"lteer"is good because we can rearrange it to form"leetr". "letl"is not good because we cannot rearrange it to contain"leet"as a substring.
Return the total number of good strings of length n.
Since the answer may be large, return it modulo 10^9 + 7.
A substring is a contiguous sequence of characters within a string.
Example 1:
Input: n = 4
Output: 12
Explanation: The 12 strings which can be rearranged to have "leet" as a substring are: "eelt", "eetl", "elet", "elte", "etel", "etle", "leet", "lete", "ltee", "teel", "tele", and "tlee".
Example 2:
Input: n = 10
Output: 83943898
Explanation: The number of strings with length 10 which can be rearranged to have "leet" as a substring is 526083947580. Hence the answer is 526083947580 % (10^9 + 7) = 83943898.
Constraints:
1 <= n <= 10^5
Solution
Approach: Memoized Search
A string can be rearranged to contain "leet" exactly when it has at least one l, at least two e and at least one t. Let dfs(i, l, e, t) be the number of ways to fill the remaining i positions, given that we already have l (capped at 1) letters l, e (capped at 2) letters e and t (capped at 1) letters t. The answer is dfs(n, 0, 0, 0).
If i == 0, return 1 when l == 1, e == 2 and t == 1, else 0. Otherwise the next character can be:
- one of the 23 other letters:
23 * dfs(i - 1, l, e, t), l,eort: the same call with the corresponding counter increased (up to its cap).
Sum the four terms modulo 10^9 + 7 and memoize on (i, l, e, t).
Complexity: O(n) time and space (there are only 12 states per length).
from functools import lru_cache
class Solution:
def stringCount(self, n: int) -> int:
@lru_cache(None)
def dfs(i: int, l: int, e: int, t: int) -> int:
if i == 0:
return int(l == 1 and e == 2 and t == 1)
a = dfs(i - 1, l, e, t) * 23 % mod
b = dfs(i - 1, min(1, l + 1), e, t)
c = dfs(i - 1, l, min(2, e + 1), t)
d = dfs(i - 1, l, e, min(1, t + 1))
return (a + b + c + d) % mod
mod = 10**9 + 7
return dfs(n, 0, 0, 0)