Taro Logo

Number of Strings Which Can Be Rearranged to Contain Substring

Medium
Asked by:
Meesho
0 views
Topics:
Dynamic Programming

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 109 + 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 % (109 + 7) = 83943898.

Constraints:

  • 1 <= n <= 105

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What is the maximum value of $n$ for which we need to calculate the result?
  2. Are we restricted exclusively to the 26 lowercase English letters ('a' through 'z')?
  3. Does the definition of 'substring' mean that the characters 'l', 'e', 'e', and 't' must appear contiguously in that exact order?
  4. Since the answer can be very large, should we return the result modulo $10^9 + 7$?
  5. Is $n$ guaranteed to be at least 4 (the minimum length required to contain the substring 'leet'), and how should we handle values of $n$ less than 4?

Brute Force Solution

Approach

To solve this problem using the brute force approach, we need to examine every single possible way to rearrange the letters of a word of a given length. Then, we inspect each newly formed arrangement to see if it contains the specific target sequence of letters we are looking for.

Here's how the algorithm would work step-by-step:

  1. Start by generating every possible combination of letter orders for a word of the given length.
  2. Make sure to include all duplicates and variations, leaving no potential rearrangement out.
  3. Take the first rearranged word from your giant list of possibilities.
  4. Check that word carefully to see if the target sequence appears inside it in the correct order.
  5. If the target sequence is found, keep a mental point for this successful arrangement.
  6. If the target sequence is not found, discard this arrangement and move along.
  7. Repeat the checking process for every single rearrangement on your list until you have looked at all of them.
  8. Finally, count up all the successful arrangements you found and report that total as your answer.

Code Implementation

import itertools


def count_rearrangements_brute_force(string_length):
    alphabet_string = "abcdefghijklmnopqrstuvwxyz"
    target_substring = "leetcode"
    successful_count = 0
    
    # Generate all possible letter permutations to evaluate every single rearrangement option
    for permutation_tuple in itertools.product(alphabet_string, repeat=string_length):
        
        current_word = "".join(permutation_tuple)
        
        # Search for the target substring because we only want to count arrangements containing it
        if target_substring in current_word:
            successful_count += 1
            
    return successful_count

Big(O) Analysis

Time Complexity
O(n * 26^n) – To generate every possible rearrangement of a word of length n using a standard alphabet of 26 letters, there are 26^n total permutations. For each generated string, we must perform a substring check that takes up to O(n) time to see if the target sequence is present. This leads to approximately n * 26^n total operations, which simplifies to the exponential Big O time complexity of O(n * 26^n).
Space Complexity
O(N * 4^N) – The brute force approach requires generating and storing every possible rearrangement of a string of length N, resulting in 4^N total permutations, each occupying O(N) space to hold the string characters in memory. This massive list of generated arrangements creates an auxiliary data structure whose size grows exponentially with the input length N. Additionally, the recursion stack and temporary variables used during generation scale linearly with N, but are completely dominated by the storage needed for all permutations. Consequently, the total extra memory consumed by the algorithm simplifies to O(N * 4^N) in Big O notation.

Optimal Solution

Approach

Instead of trying to check every possible rearrangement of letters, which takes way too long, we use a clever subtraction shortcut. We calculate the total number of all possible letter combinations and subtract the ones that do not contain the target word, leaving us with the exact answer we want.

Here's how the algorithm would work step-by-step:

  1. Figure out the total number of possible combinations you can make if you are allowed to pick any letter of the alphabet for every spot in the word.
  2. Identify the unwanted scenarios: combinations where the target word never appears at all.
  3. Count how many combinations completely miss the first required letter of the target word.
  4. Count how many combinations completely miss the second required letter of the target word.
  5. Count how many combinations completely miss the third required letter of the target word.
  6. Combine the counts of these missing pieces carefully, making sure not to double count situations where multiple required letters are missing at the same time.
  7. Subtract this total count of unwanted combinations from the grand total of all possible combinations to find the exact number of valid arrangements.

Code Implementation

def string_count(string_length):
    modulus_value = 10**9 + 7

    # Total possible combinations for a string of length n using 26 alphabet letters.
    total_combinations = pow(26, string_length, modulus_value)

    # Exclude combinations missing at least one required character of 'leet'.
    missing_at_least_one = (
        pow(25, string_length, modulus_value)
        + pow(25, string_length, modulus_value)
        + pow(25, string_length, modulus_value)
        + pow(26, string_length, modulus_value)
    )

    # Add back over-subtractions due to inclusion-exclusion principle.
    overlap_corrections = (
        pow(24, string_length, modulus_value)
        + pow(24, string_length, modulus_value)
        + pow(25, string_length, modulus_value)
        + pow(24, string_length, modulus_value)
        + pow(25, string_length, modulus_value)
        + pow(25, string_length, modulus_value)
    )

    # Account for triple intersections in the inclusion-exclusion principle.
    triple_intersections = (
        pow(23, string_length, modulus_value)
        + pow(24, string_length, modulus_value)
        + pow(24, string_length, modulus_value)
        + pow(24, string_length, modulus_value)
    )

    # Adjust for quadruple intersections to finalize unwanted combinations count.
    quad_intersections = pow(23, string_length, modulus_value)

    unwanted_combinations = (
        missing_at_least_one
        - overlap_corrections
        + triple_intersections
        - quad_intersections
    ) % modulus_value

    # Subtract unwanted combinations from the total to isolate valid arrangements.
    final_answer = (total_combinations - unwanted_combinations) % modulus_value

    return final_answer

Big(O) Analysis

Time Complexity
O(n) – The input size is represented by n, which is the length of the string to be generated. The algorithm computes the total combinations and subtracts unwanted scenarios involving missing target letters using basic arithmetic and exponentiation. Since the target substring is fixed in length at three characters, the operations required to calculate these combinations scale linearly with n. This results in approximately a constant number of arithmetic steps executed proportionally to n, which simplifies to O(n).
Space Complexity
O(1) – To calculate the total combinations and subtract the unwanted scenarios, the algorithm only uses a few primitive variables like integer counters and mathematical accumulators. No dynamic data structures, recursive call stacks, or auxiliary arrays that scale with the input length N are needed. Therefore, the extra memory required remains constant regardless of how large N grows.

Edge Cases

Input n less than 4
How to Handle:
The solution must return zero immediately because a string of length less than 4 cannot contain the 4-character substring leet.
Input n exactly equal to 4
How to Handle:
The recurrence relation or combinatorics must correctly evaluate to exactly 1 for the sole valid string leet.
Maximum possible constraint values for n
How to Handle:
We must use modular arithmetic at every step of the exponentiation or dynamic programming to prevent integer overflow and handle large numbers efficiently.
Language-specific large integer handling in languages like Python versus C++ or Java
How to Handle:
Python handles arbitrarily large integers natively, whereas C++ and Java require explicit 64-bit integers and modulo operations during intermediate multiplications.
Complementary counting approach avoiding explicit string generation
How to Handle:
Instead of generating strings which causes exponential time complexity, we calculate the total possible strings and subtract strings lacking leet using dynamic programming or matrix exponentiation for logarithmic time complexity.
Handling state transitions for valid substring prefix matches
How to Handle:
The dynamic programming state must accurately track how many characters of the target substring leet have been matched consecutively.