Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Program to count sorted vowel strings in Python
Suppose we have a number n, we have to find the number of strings of size n that consist only of vowels (a, e, i, o, u) and they are lexicographically sorted. We can say that a string s is lexicographically sorted when for all valid index i, s[i] is the same as or comes before s[i+1] in the alphabet.
So, if the input is like n = 2, then the output will be 15 because there are many strings like ["aa", "ae", "ai", "ao", "au", "ee", "ei", "eo", "eu", "ii", "io", "iu", "oo", "ou", "uu"].
Understanding the Approach
This problem can be solved using dynamic programming. We'll track how many valid strings can be formed ending with each vowel at each position.
Algorithm Steps
To solve this, we will follow these steps ?
- If n is same as 1, then return 5 (one string for each vowel)
- Create a count array of size 6, initially filled with 1
- For each position from 3 to n, update counts:
- count[1] := count[1] + count[2] + count[3] + count[4] + count[5]
- count[2] := count[2] + count[3] + count[4] + count[5]
- count[3] := count[3] + count[4] + count[5]
- count[4] := count[4] + count[5]
- Calculate total by summing all valid combinations
Example
Let us see the following implementation to get better understanding ?
def solve(n):
if n == 1:
return 5
count = [1 for i in range(6)]
for i in range(3, n + 1):
count[1] = count[1] + count[2] + count[3] + count[4] + count[5]
count[2] = count[2] + count[3] + count[4] + count[5]
count[3] = count[3] + count[4] + count[5]
count[4] = count[4] + count[5]
total = 0
for i in range(1, 6):
total += i * count[i]
return total
n = 2
print(solve(n))
The output of the above code is ?
15
How It Works
The algorithm uses dynamic programming where count[i] represents the number of ways to form valid strings ending with the i-th vowel. Since strings must be lexicographically sorted, a vowel can only be followed by vowels that come later in the alphabet.
Testing with Different Values
def solve(n):
if n == 1:
return 5
count = [1 for i in range(6)]
for i in range(3, n + 1):
count[1] = count[1] + count[2] + count[3] + count[4] + count[5]
count[2] = count[2] + count[3] + count[4] + count[5]
count[3] = count[3] + count[4] + count[5]
count[4] = count[4] + count[5]
total = 0
for i in range(1, 6):
total += i * count[i]
return total
# Test with different values
for n in range(1, 5):
print(f"n = {n}: {solve(n)} sorted vowel strings")
n = 1: 5 sorted vowel strings n = 2: 15 sorted vowel strings n = 3: 35 sorted vowel strings n = 4: 70 sorted vowel strings
Conclusion
This dynamic programming solution efficiently counts lexicographically sorted vowel strings by tracking valid combinations at each position. The time complexity is O(n) and space complexity is O(1).
