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

Master LeetCode problem 2930 (Number of Strings Which Can Be Rearranged to Contain Substring), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

2930. Number of Strings Which Can Be Rearranged to Contain Substring

Problem Explanation

Explanation

To solve this problem, we can use dynamic programming to count the number of good strings of length n that can be rearranged to contain the substring "leet". We can iterate through all possible combinations of characters in the string and keep track of the count of good strings that can be formed.

  1. Initialize a 2D array dp where dp[i][j] represents the number of good strings of length i that end with character j.
  2. Iterate through all possible characters for each position in the string and update the dp array accordingly.
  3. At the end of the iteration, sum up the counts in the last row of the dp array to get the total number of good strings of length n.
  4. Return the count modulo 10^9 + 7.

Time complexity: O(n) Space complexity: O(26 * n)

Solution Code

class Solution {
    public int countGoodStrings(int n) {
        int mod = 1000000007;
        int[][] dp = new int[n + 1][26];
        dp[0][0] = 1;
        
        for (int i = 1; i <= n; i++) {
            for (int j = 0; j < 26; j++) {
                for (int k = 0; k < 26; k++) {
                    if (j != k && !(j == 'l' - 'a' && k == 'e' - 'a')) {
                        dp[i][j] = (dp[i][j] + dp[i - 1][k]) % mod;
                    }
                }
            }
        }
        
        int ans = 0;
        for (int j = 0; j < 26; j++) {
            ans = (ans + dp[n][j]) % mod;
        }
        
        return ans;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 2930 (Number of Strings Which Can Be Rearranged to Contain Substring)?

This page provides optimized solutions for LeetCode problem 2930 (Number of Strings Which Can Be Rearranged to Contain Substring) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 2930 (Number of Strings Which Can Be Rearranged to Contain Substring)?

The time complexity for LeetCode 2930 (Number of Strings Which Can Be Rearranged to Contain Substring) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 2930 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2930 in Java, C++, or Python.

Back to LeetCode Solutions