Count Sorted Vowel Strings — LeetCode 1641 Python Solution
- Problem
- #1641
- Pattern
- Dynamic Programming
- Reading time
- 2 min
- Source
- leetcode.com
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
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
| Measure | Complexity |
|---|---|
| Time | O(n·m) (typical) |
| Space | O(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.