Count Sorted Vowel Strings — LeetCode 1641 Python Solution

MediumMathDynamic ProgrammingCombinatorics
Problem
#1641
Reading time
2 min

The problem

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

Input
n = 1
Output
5
Explanation
The 5 sorted strings that consist of vowels only are ["a","e","i","o","u"].

Python solution

Python
class Solution:
    def countVowelStrings(self, n: int) -> int:
        @cache
        def dfs(i, j):
            return 1 if i >= n else sum(dfs(i + 1, k) for k in range(j, 5))

        return dfs(0, 0)

Complexity

MeasureComplexity
TimeO(n·m) (typical)
SpaceO(n·m) or optimized auxiliary

Pattern: Dynamic Programming

Define a state, write the transition, and stop recomputing the same subproblem. LeetCode 1641. Count Sorted Vowel Strings is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Dynamic Programming.

The dynamic programming guide has the Python template for the pattern and the 481 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1641. Count Sorted Vowel Strings?
LeetCode 1641. Count Sorted Vowel Strings is rated Medium on LeetCode.
What topics does LeetCode 1641. Count Sorted Vowel Strings cover?
LeetCode 1641. Count Sorted Vowel Strings is tagged Math, Dynamic Programming and Combinatorics on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview