We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Number of Strings Which Can Be Rearranged to Contain Substring

Difficulty: Medium


Problem Description

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. Return the total number of good strings of length n. Since the answer may be large, return it modulo 10^9 + 7.


Key Insights

  • A good string must contain at least the characters 'l', 'e', 'e', 't' in the required frequencies.
  • For lengths less than 4, it's impossible to contain the substring "leet".
  • For lengths greater than or equal to 4, we need to calculate the number of arrangements of the remaining characters while ensuring "leet" is present.
  • The remaining characters can be any lowercase letters, and their arrangements can be calculated using combinatorial methods.

Space and Time Complexity

Time Complexity: O(n)
Space Complexity: O(1)


Solution

To solve this problem, we can use combinatorial mathematics to count the arrangements of the characters. The main idea is to:

  1. Calculate the total number of letters in the string.
  2. Ensure "leet" is included, then calculate the arrangements of the remaining characters.
  3. Use the factorial to compute permutations, adjusting for the repeated characters 'e'.
  4. Handle large numbers using modulo 10^9 + 7.

We will use the formula for permutations: P(n, r) = n! / (n - r)!

The approach involves:

  • Counting how many total letters can be used (n - 4 for the extra letters).
  • Using combinatorial counting to find the valid arrangements.

Code Solutions

def countGoodStrings(n):
    MOD = 10**9 + 7

    if n < 4:
        return 0

    # Calculate factorials and factorial inverses
    fact = [1] * (n + 1)
    for i in range(2, n + 1):
        fact[i] = fact[i - 1] * i % MOD

    # Count total arrangements of the string
    total_good_strings = fact[n - 4] * fact[4] % MOD

    # Calculate ways to arrange (n - 4) letters with 4 fixed letters
    total_good_strings *= (26 ** (n - 4)) % MOD
    total_good_strings %= MOD

    return total_good_strings
← Back to All Questions