LeetCode 1220: Count Vowels Permutation Solution

Master LeetCode problem 1220 (Count Vowels Permutation), a hard 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.

1220. Count Vowels Permutation

Problem Explanation

Explanation

To solve this problem, we can use dynamic programming to count the number of strings that can be formed of length n satisfying the given rules. We can define a 2D array dp where dp[i][j] represents the number of valid strings of length i ending with character j.

We can then iterate through each position i and each possible ending vowel j, and update the count based on the rules mentioned in the problem statement.

The final answer will be the sum of all counts in the last row of the dp array modulo 10^9 + 7.

  • Time complexity: O(n)
  • Space complexity: O(n)

Solution Code

class Solution {
    public int countVowelPermutation(int n) {
        long[][] dp = new long[n + 1][5];
        int mod = 1000000007;
        
        for (int i = 0; i < 5; i++) {
            dp[1][i] = 1;
        }
        
        for (int i = 2; i <= n; i++) {
            dp[i][0] = (dp[i - 1][1] + dp[i - 1][2] + dp[i - 1][4]) % mod;
            dp[i][1] = (dp[i - 1][0] + dp[i - 1][2]) % mod;
            dp[i][2] = (dp[i - 1][1] + dp[i - 1][3]) % mod;
            dp[i][3] = dp[i - 1][2] % mod;
            dp[i][4] = (dp[i - 1][2] + dp[i - 1][3]) % mod;
        }
        
        long count = 0;
        for (int i = 0; i < 5; i++) {
            count = (count + dp[n][i]) % mod;
        }
        
        return (int) count;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 1220 (Count Vowels Permutation)?

This page provides optimized solutions for LeetCode problem 1220 (Count Vowels Permutation) 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 1220 (Count Vowels Permutation)?

The time complexity for LeetCode 1220 (Count Vowels Permutation) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 1220 on DevExCode?

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

Back to LeetCode Solutions