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"].

To solve this, we will follow these steps −

  • if n is same as 1, then
    • return 5
  • count := an array of size 6, and initially filled with 1
  • for i in range 3 to n, do
    • 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 to 5, do
    • total := total + i*count[i]
  • return total

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))

Input

2

Output

15

Updated on: 05-Oct-2021

521 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements