Skip to content

Latest commit

 

History

History
57 lines (42 loc) · 1.48 KB

008.md

File metadata and controls

57 lines (42 loc) · 1.48 KB

Difficulty: 🟡 Medium

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.

Examples:

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

Solutions

DP solution with recursion

class Solution:
    def countVowelStrings(self, n: int) -> int:
        base = {0: [0], 1: [5], 2: [1, 2, 3, 4, 5]}
        def count(k):
            if k in base:
                return base[k]
            
            prev = count(k-1)
            for i in range(1, len(prev)):
                prev[i] = prev[i] + prev[i-1]
            return prev
                
        return sum(count(n))

NB: If you want to get community points please suggest solutions in other languages as merge requests.