LeetCode 1641: Count Sorted Vowel Strings
LeetCode 1641 Solution Explanation
Explanation
To solve this problem, we can use dynamic programming. We can maintain a 2D array dp
where dp[i][j]
represents the number of valid strings of length i+1
ending with the vowel at index j
(0-indexed) in the vowels array ['a', 'e', 'i', 'o', 'u']
. We can calculate the values in the dp
array iteratively based on the previous values.
At each step, the number of valid strings ending with a vowel at index j
is the sum of the number of valid strings ending with a vowel at index j
or any vowel before it. This is because the strings are required to be lexicographically sorted.
Finally, we sum up the values in the last row of the dp
array to get the total number of valid strings of length n
.
Time complexity: O(n)
Space complexity: O(5n) = O(n)
LeetCode 1641 Solutions in Java, C++, Python
class Solution {
public int countVowelStrings(int n) {
int[][] dp = new int[n][5];
for (int i = 0; i < 5; i++) {
dp[0][i] = 1;
}
for (int i = 1; i < n; i++) {
for (int j = 0; j < 5; j++) {
for (int k = 0; k <= j; k++) {
dp[i][j] += dp[i-1][k];
}
}
}
int result = 0;
for (int i = 0; i < 5; i++) {
result += dp[n-1][i];
}
return result;
}
}
Interactive Code Editor for LeetCode 1641
Improve Your LeetCode 1641 Solution
Use the editor below to refine the provided solution for LeetCode 1641. Select a programming language and try the following:
- Add import statements if required.
- Optimize the code for better time or space complexity.
- Add test cases to validate edge cases and common scenarios.
- Handle error conditions or invalid inputs gracefully.
- Experiment with alternative approaches to deepen your understanding.
Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.
Loading editor...