Number of Strings Which Can Be Rearranged to Contain Substring — LeetCode 2930 Python Solution
- Problem
- #2930
- Pattern
- Dynamic Programming
- Reading time
- 3 min
- Source
- leetcode.com
The problem
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.
Example
- 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".
Python solution
class Solution:
def stringCount(self, n: int) -> int:
@cache
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)Complexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(n) auxiliary |
Pattern: Dynamic Programming
Define a state, write the transition, and stop recomputing the same subproblem. LeetCode 2930. Number of Strings Which Can Be Rearranged to Contain Substring is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Dynamic Programming.
The dynamic programming guide has the Python template for the pattern and the 481 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 2930. Number of Strings Which Can Be Rearranged to Contain Substring?
- LeetCode 2930. Number of Strings Which Can Be Rearranged to Contain Substring is rated Medium on LeetCode.
- What is the time complexity of LeetCode 2930. Number of Strings Which Can Be Rearranged to Contain Substring?
- The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 2930. Number of Strings Which Can Be Rearranged to Contain Substring?
- The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 2930. Number of Strings Which Can Be Rearranged to Contain Substring cover?
- LeetCode 2930. Number of Strings Which Can Be Rearranged to Contain Substring is tagged Math, Dynamic Programming and Combinatorics on LeetCode.