math
dp
]
Leetcode 1641. Count Sorted Vowel Strings
https://leetcode.com/problems/count-sorted-vowel-strings
Actually, this is very classical combinatorical problem, which can be solved, using so-called stars and bars method: https://en.wikipedia.org/wiki/Stars_and_bars_(combinatorics). Imagine, that we have string aa..aee..eii..ioo..ouu..u
, where we have some numbers of a, e, i, o
and u
. Then we can look at this problem in the following way: we have n + 4
, places, and on some of them we need to put bars |
, for example aaaeeiuu
is corresponding to ***|**|*||**
. So, final number of solutions is number of combinations from n+4
to 4,
which can be evaluated as (n+4)!/n!/4!
.
Complexity: time and space complexity is O(1)
, because n
is small. One quick optimization is to use (n+4)*(n+3)*(n+2)*(n+1)//4
formula, which will work faster for big n
, but given problem constraints different is negligible.
class Solution:
def countVowelStrings(self, n):
return factorial(4+n)//factorial(4)//factorial(n)
If you like the solution, you can upvote it on leetcode discussion section: Problem 1641