#2586

Count the Number of Vowel Strings in Range

Easy
ArrayStringCountingHash SetArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

The optimal solution is similar to the brute force approach but focuses on reducing unnecessary checks by directly accessing the first and last characters of each string. This ensures we only loop through the relevant range once.

⚙️

Algorithm

6 steps
  1. 1Step 1: Create a set of vowels for quick lookup.
  2. 2Step 2: Initialize a counter to zero.
  3. 3Step 3: Loop through the words array from index 'left' to 'right'.
  4. 4Step 4: For each word, check if the first and last characters are vowels using the set.
  5. 5Step 5: If both conditions are met, increment the counter.
  6. 6Step 6: Return the counter.
solution.py7 lines
1def countVowelStrings(words, left, right):
2    vowels = {'a', 'e', 'i', 'o', 'u'}
3    count = 0
4    for i in range(left, right + 1):
5        if words[i][0] in vowels and words[i][-1] in vowels:
6            count += 1
7    return count

Complexity note: The time complexity remains O(n) as we still iterate through the range once. The space complexity is O(1) since we only use a constant amount of space for the counter and the vowel set.

  • 1Vowel checking can be efficiently done using a set for O(1) lookups.
  • 2The problem can be solved in a single pass through the specified range.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.