We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Count Sorted Vowel Strings

Number: 1761

Difficulty: Medium

Paid? No

Companies: Apple


Problem Description

Given an integer n, count the number of strings of length n that consist only of vowels ('a', 'e', 'i', 'o', 'u') and are lexicographically sorted. A string is lexicographically sorted if every character is the same as or comes before the next character in alphabetical order.


Key Insights

  • The string must be non-decreasing; once a vowel is chosen, further vowels cannot be lower in the alphabet.
  • This is equivalent to finding combinations with repetition, where we choose n vowels from 5 with the constraint of sorted order.
  • The problem can be solved using a combinatorial formula: the answer is "n+4 choose 4".
  • A dynamic programming approach is also possible, but the combinatorial solution is more optimal and straightforward.

Space and Time Complexity

Time Complexity: O(n) (or O(1) if using the combinatorial formula since the loop runs only a constant number of times) Space Complexity: O(1)


Solution

The problem can be modeled as a combination with repetition: choosing n items from 5 types (vowels) where order does not matter. The number of ways to do this is given by the binomial coefficient C(n+5-1, 5-1), which simplifies to C(n+4, 4). To compute this result, we can iterate from 1 to 4 and multiply/divide accordingly. This approach avoids calculating factorials directly and prevents potential overflow issues for the given constraint (n ≤ 50).


Code Solutions

def countVowelStrings(n):
    # Calculate the binomial coefficient C(n+4, 4)
    # Initialize result as 1
    res = 1
    # Multiply and divide iteratively to compute combination
    for i in range(1, 5):
        res = res * (n + i) // i
    return res

# Example usages:
print(countVowelStrings(1))  # Expected output: 5
print(countVowelStrings(2))  # Expected output: 15
print(countVowelStrings(33)) # Expected output: 66045
← Back to All Questions