Number of Strings Which Can Be Rearranged to Contain Substring — LeetCode 2930 Python Solution

MediumMathDynamic ProgrammingCombinatorics
Problem
#2930
Reading time
3 min

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

Python
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

MeasureComplexity
TimeO(n)
SpaceO(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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview