Count Sorted Vowel Strings Problem
Description
LeetCode Problem 1641.
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
Solution
Approach: Dynamic Programming by Last Vowel
A sorted string can only grow by a vowel that is the same as or later than its last one. So all we need to know about a string is its length and its last vowel.
Let f[j] be the number of sorted strings of the current length that end with vowel j (a = 0, ..., u = 4). For length 1, f = [1, 1, 1, 1, 1]. To get one character longer, vowel j can be added after any string that ends with vowel 0..j, so the new f[j] is the sum of the old f[0..j], a prefix sum. Computing it in place from left to right, f[j] += f[j-1], does exactly that.
After n - 1 steps, the answer is the sum of f. For n = 2 the steps give [1, 2, 3, 4, 5], which adds up to 15.
(This also equals C(n + 4, 4): choosing how many of each vowel to use, which fixes the sorted string.)
Complexity: O(n) time (5 additions per length) and O(1) extra space.
class Solution:
def countVowelStrings(self, n: int) -> int:
# f[j] = number of sorted strings of the current length that end with vowel j
f = [1] * 5
for _ in range(n - 1):
# Vowel j can follow any string ending with vowel 0..j: a prefix sum.
for j in range(1, 5):
f[j] += f[j - 1]
return sum(f)