[Solution] Count the Number of Vowel Strings in Range Solution

Count the Number of Vowel Strings in Range Solution

You are given a 0-indexed array of string words and two integers left and right.

A string is called a vowel string if it starts with a vowel character and ends with a vowel character where vowel characters are 'a''e''i''o', and 'u'.

Return the number of vowel strings words[i] where i belongs to the inclusive range [left, right].

 

Example 1:Count the Number of Vowel Strings in Range Solution

Input: words = ["are","amy","u"], left = 0, right = 2
Output: 2
Explanation: 
- "are" is a vowel string because it starts with 'a' and ends with 'e'.
- "amy" is not a vowel string because it does not end with a vowel.
- "u" is a vowel string because it starts with 'u' and ends with 'u'.
The number of vowel strings in the mentioned range is 2.

Example 2:Count the Number of Vowel Strings in Range Solution

Input: words = ["hey","aeo","mu","ooo","artro"], left = 1, right = 4
Output: 3
Explanation: 
- "aeo" is a vowel string because it starts with 'a' and ends with 'o'.
- "mu" is not a vowel string because it does not start with a vowel.
- "ooo" is a vowel string because it starts with 'o' and ends with 'o'.
- "artro" is a vowel string because it starts with 'a' and ends with 'o'.
The number of vowel strings in the mentioned range is 3.

 

Constraints:Count the Number of Vowel Strings in Range Solution

  • 1 <= words.length <= 1000
  • 1 <= words[i].length <= 10
  • words[i] consists of only lowercase English letters.
  • 0 <= left <= right < words.length

Solution:Count the Number of Vowel Strings in Range Solution

To solve this problem, we can iterate through the words in the given range [left, right], and for each word, we can check if it starts and ends with a vowel character. If it does, we count it as a vowel string.

Here’s the algorithm:

  1. Initialize a count variable to 0.
  2. Iterate over the range [left, right] and for each index i, do the following: a. If the word at index i starts with a vowel character and ends with a vowel character, increment the count.
  3. Return the count.
We can use the is_vowel() helper function to check if a character is a vowel or not. The function returns True if the character is a vowel and False otherwise.Count the Number of Vowel Strings in Range Solution

Here’s the Python code that implements the above algorithm:

def is_vowel(c):
return c in [‘a’, ‘e’, ‘i’, ‘o’, ‘u’]

def count_vowel_strings(words, left, right):
count = 0
for i in range(left, right+1):
word = words[i]
if is_vowel(word[0]) and is_vowel(word[-1]):
count += 1
return count

Count the Number of Vowel Strings in Range Solution

Leave a Comment