Count Sorted Vowel Strings

medium math dp combinatorics

Problem

Return the number of strings of length n consisting only of vowels (a, e, i, o, u) that are sorted in lexicographic order.

Inputn = 2
Output15
aa, ae, ai, ao, au, ee, ei, eo, eu, ii, io, iu, oo, ou, uu.

def count_vowel_strings(n):
    # dp[v] = number of sorted strings ending with vowel v (a=0..u=4)
    dp = [1] * 5
    for _ in range(n - 1):
        for v in range(3, -1, -1):
            dp[v] += dp[v + 1]
    return sum(dp)
function countVowelStrings(n) {
  const dp = [1, 1, 1, 1, 1];
  for (let k = 1; k < n; k++)
    for (let v = 3; v >= 0; v--)
      dp[v] += dp[v + 1];
  return dp.reduce((a, b) => a + b, 0);
}
class Solution {
    public int countVowelStrings(int n) {
        int[] dp = {1, 1, 1, 1, 1};
        for (int k = 1; k < n; k++)
            for (int v = 3; v >= 0; v--)
                dp[v] += dp[v + 1];
        int s = 0;
        for (int x : dp) s += x;
        return s;
    }
}
int countVowelStrings(int n) {
    int dp[5] = {1, 1, 1, 1, 1};
    for (int k = 1; k < n; k++)
        for (int v = 3; v >= 0; v--)
            dp[v] += dp[v + 1];
    int s = 0;
    for (int x : dp) s += x;
    return s;
}
Time: O(n) Space: O(1)