Given an integer n, return the number of strings of length n that consist only of vowels (a, e, i, o, u) and are lexicographically sorted.
A string s is lexicographically sorted if for all valid i, s[i] is the same as or comes before s[i+1] in the alphabet.
Example 1:
Input: n = 1
Output: 5
Explanation: The 5 sorted strings that consist of vowels only are ["a","e","i","o","u"].
Example 2:
Input: n = 2 Output: 15 Explanation: The 15 sorted strings that consist of vowels only are ["aa","ae","ai","ao","au","ee","ei","eo","eu","ii","io","iu","oo","ou","uu"]. Note that "ea" is not a valid string since 'e' comes after 'a' in the alphabet.
Example 3:
Input: n = 33 Output: 66045
Constraints:
1 <= n <= 50 We can use dynamic programming to solve this problem whereby we maintain a table dp[i][j] where i is the length of the string and j is the vowel index from the sorted vowels list [0: 'a', 1: 'e', 2: 'i', 3: 'o', 4: 'u']. Each cell dp[i][j] represents the number of valid strings of length i using the vowels from index j to the end. We initialize the base case for strings of length 1 and fill the table iteratively.
The algorithm initializes a table where dp[i][j] stores numbers of strings of length i from vowel j onward. It calculates each table entry by summing up the possibilities of extending strings of length i-1 with each vowel.
C++
Java
Python
C#
JavaScript
Time Complexity: O(n * 5 * 5) = O(n), as we have nested loops running across vowels and length.
Space Complexity: O(n * 5), for storing the table.
Instead of counting strings iteratively, we can view the problem as a mathematical combination problem. Since the string is lexicographically sorted, the placement of 'n' vowels among 'a', 'e', 'i', 'o', 'u' is equivalent to distributing 'n' identical items into 5 distinct groups (vowel buckets). We use the combinatorial formula: C(n + m - 1, m - 1) where 'm' is the number of distinct vowels.
This solution provides a direct combinatory calculation using the formula for combinations. The helper function computes combinations recursively.
C++
Java
Python
C#
JavaScript
Time Complexity: O(n), due to the recursive calculation of combination.
Space Complexity: O(n), for the recursive call stack.
| Approach | Complexity |
|---|---|
| Dynamic Programming Approach | Time Complexity: O(n * 5 * 5) = O(n), as we have nested loops running across vowels and length. |
| Combinatorial Mathematics Approach | Time Complexity: O(n), due to the recursive calculation of combination. |
Leetcode 1641. Count Sorted Vowel Strings • Fraz • 18,298 views views
Watch 9 more video solutions →Practice Count Sorted Vowel Strings with our built-in code editor and test cases.
Practice on FleetCode