Difficulty: Easy | Acceptance: 74.30% | Paid: No Topics: Array, String, Counting
You are given a 0-indexed string array 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. The vowel characters are ‘a’, ‘e’, ‘i’, ‘o’, and ‘u’.
Return the number of vowel strings in the range [left, right].
- Examples
- Constraints
- Iterative Approach
- Functional Approach
Examples
Input: words = ["how","leto","let","be","code"], left = 0, right = 2
Output: 1
Explanation:
- "how" starts and ends with consonants.
- "leto" starts and ends with vowels.
- "let" starts and ends with consonants.
There is 1 vowel string in the range.
Input: words = ["are","amy","u"], left = 0, right = 2
Output: 2
Explanation:
- "are" starts and ends with vowels.
- "amy" starts with a vowel and ends with a consonant.
- "u" starts and ends with a vowel.
There are 2 vowel strings in the range.
Constraints
1 <= words.length <= 1000
1 <= words[i].length <= 10
words[i] consists of lowercase English letters.
0 <= left <= right < words.length
Iterative Approach
Intuition We simply iterate through the specified range of indices and check each word to see if it satisfies the vowel string condition.
Steps
- Define a set or string containing the vowels ‘a’, ‘e’, ‘i’, ‘o’, ‘u’.
- Initialize a counter to 0.
- Loop from index
lefttoright(inclusive). - For each word, check if the first character and the last character are present in the vowels set.
- If both are vowels, increment the counter.
- Return the counter.
python
class Solution:
def vowelStrings(self, words: list[str], left: int, right: int) -> int:
vowels = set('aeiou')
count = 0
for i in range(left, right + 1):
word = words[i]
if word[0] in vowels and word[-1] in vowels:
count += 1
return countComplexity
- Time: O(N), where N is the number of words in the range (right - left + 1).
- Space: O(1), as we only use a fixed-size set for vowels and a counter.
- Notes: This is the most straightforward approach.
Functional Approach
Intuition We utilize functional programming constructs like streams, filters, or list comprehensions to declaratively filter the words that match the criteria and count them.
Steps
- Define the vowels.
- Create a sub-list or stream of words from index
lefttoright. - Filter this collection to keep only words where the first and last characters are vowels.
- Return the size or count of the filtered collection.
python
class Solution:
def vowelStrings(self, words: list[str], left: int, right: int) -> int:
vowels = set('aeiou')
return sum(1 for w in words[left:right+1] if w[0] in vowels and w[-1] in vowels)Complexity
- Time: O(N), where N is the number of words in the range.
- Space: O(1) auxiliary space, though
slicein JS/TS creates a shallow copy O(N). - Notes: More concise syntax, often preferred in modern codebases for readability.