Browse curriculum

Count Vowels in Ranges

Count Vowels in Ranges: answer range queries counting the words that start and end with a vowel: one pass to build a prefix count, then one subtraction per query.

Problem Understanding

You are given a string array words and a 2D array queries. Each query [l, r] asks for the number of strings in words[l...r] that start and end with a vowel.

We need to answer many queries efficiently.

Strategy

  1. Preprocessing: Create a boolean/integer array is_valid where is_valid[i] = 1 if words[i] starts and ends with a vowel, else 0.
  2. Prefix Sum: Compute prefix sum P of is_valid. P[i] = count of valid words in words[0...i-1].
  3. Query: Answer for [l, r] is P[r+1] - P[l].
  • Vowels: a, e, i, o, u

Interactive Visualization

5 WORDS · 3 QUERIES

ALLOCATE PREFIX

words

aba

0

bcb

1

ece

2

aa

3

e

4

valid (0/1)

-

0

-

1

-

2

-

3

-

4

prefix

0

0

0

1

0

2

0

3

0

4

0

5

Query

:

Answer

:

ans

No query answered yet

 

Allocate prefix with 6 zeros: prefix[i] will count the vowel strings among the first i words

Next

"aba" starts with 'a' and ends with 'a': both vowels, so it counts

Free preview: the first 5 of 15 steps

Words

Queries

See how we can answer multiple range queries in O(1) time after O(N) preprocessing.

Edge Cases

Consider:

  • Empty Queries: Return empty array.

  • Single Word: Range [0, 0].

  • No Vowels: Prefix sum remains 0.

Dry Run

Words: ['aba', 'bcb', 'ece', 'aa', 'e']. Valid: [1, 0, 1, 1, 1].
Prefix P: [0, 1, 1, 2, 3, 4] (size N+1)

Query Formula P[R+1] - P[L] Values Result
[0, 2] P[3] - P[0] 2 - 0 2 (aba, ece)
[1, 4] P[5] - P[1] 4 - 1 3 (ece, aa, e)

Solution

O(N + Q) Time.

Count Vowels in Ranges Code
1var vowelStrings = function(words, queries) {
2 const vowels = new Set(['a', 'e', 'i', 'o', 'u']);
3 const n = words.length;
4 const prefix = new Array(n + 1).fill(0);
5
6 for (let i = 0; i < n; i++) {
7 const w = words[i];
8 const valid = vowels.has(w[0]) && vowels.has(w[w.length - 1]);
9 prefix[i+1] = prefix[i] + (valid ? 1 : 0);
10 }
11
12 const ans = [];
13 for (const [l, r] of queries) {
14 ans.push(prefix[r+1] - prefix[l]);
15 }
16 return ans;
17};

Count Vowels in Ranges in Python, Java, C++, TypeScript and C

Count Vowels in Ranges in Python
class Solution:
    def vowelStrings(self, words: List[str], queries: List[List[int]]) -> List[int]:
        vowels = {'a', 'e', 'i', 'o', 'u'}
        n = len(words)
        prefix = [0] * (n + 1)
        
        for i in range(n):
            w = words[i]
            is_valid = 1 if w[0] in vowels and w[-1] in vowels else 0
            prefix[i+1] = prefix[i] + is_valid
            
        ans = []
        for l, r in queries:
            ans.append(prefix[r+1] - prefix[l])
            
        return ans
Count Vowels in Ranges in Java
class Solution {
    public int[] vowelStrings(String[] words, int[][] queries) {
        int n = words.length;
        int[] prefix = new int[n + 1];
        Set<Character> vowels = new HashSet<>(Arrays.asList('a', 'e', 'i', 'o', 'u'));
        
        for (int i = 0; i < n; i++) {
            String w = words[i];
            boolean isValid = vowels.contains(w.charAt(0)) && vowels.contains(w.charAt(w.length() - 1));
            prefix[i+1] = prefix[i] + (isValid ? 1 : 0);
        }
        
        int[] ans = new int[queries.length];
        for (int i = 0; i < queries.length; i++) {
            ans[i] = prefix[queries[i][1] + 1] - prefix[queries[i][0]];
        }
        return ans;
    }
}
Count Vowels in Ranges in C++
class Solution {
    bool isVowel(char c) {
        return c=='a' || c=='e' || c=='i' || c=='o' || c=='u';
    }
public:
    vector<int> vowelStrings(vector<string>& words, vector<vector<int>>& queries) {
        int n = words.size();
        vector<int> prefix(n + 1, 0);
        
        for(int i=0; i<n; i++) {
            bool valid = isVowel(words[i][0]) && isVowel(words[i].back());
            prefix[i+1] = prefix[i] + (valid ? 1 : 0);
        }
        
        vector<int> ans;
        for(auto& q : queries) {
            ans.push_back(prefix[q[1] + 1] - prefix[q[0]]);
        }
        return ans;
    }
};
Count Vowels in Ranges in TypeScript
function vowelStrings(words: string[], queries: number[][]): number[] {
    const vowels = new Set(['a', 'e', 'i', 'o', 'u']);
    const n = words.length;
    const prefix: number[] = new Array(n + 1).fill(0);
    
    for (let i = 0; i < n; i++) {
        const w = words[i];
        const valid = vowels.has(w[0]) && vowels.has(w[w.length - 1]);
        prefix[i+1] = prefix[i] + (valid ? 1 : 0);
    }
    
    const ans: number[] = [];
    for (const [l, r] of queries) {
        ans.push(prefix[r+1] - prefix[l]);
    }
    return ans;
};
Count Vowels in Ranges in C
bool isVowel(char c) {
    return c=='a' || c=='e' || c=='i' || c=='o' || c=='u';
}

/**
 * Note: The returned array must be malloced, assume caller calls free().
 */
int* vowelStrings(char** words, int wordsSize, int** queries, int queriesSize, int* queriesColSize, int* returnSize) {
    int* prefix = (int*)calloc(wordsSize + 1, sizeof(int));
    
    for(int i=0; i<wordsSize; i++) {
        int len = strlen(words[i]);
        bool valid = isVowel(words[i][0]) && isVowel(words[i][len-1]);
        prefix[i+1] = prefix[i] + (valid ? 1 : 0);
    }
    
    int* ans = (int*)malloc(queriesSize * sizeof(int));
    for(int i=0; i<queriesSize; i++) {
        int l = queries[i][0];
        int r = queries[i][1];
        ans[i] = prefix[r+1] - prefix[l];
    }
    
    free(prefix);
    *returnSize = queriesSize;
    return ans;
}

More practice: DSA interview questions with answers · patterns cheat sheet

The approach, step by step

  1. Allocate the prefix array

    Create prefix with N + 1 zeros.

  2. Test and accumulate each word

    Add 1 to the running count when a word starts and ends with a vowel, and store it in prefix[i + 1].

  3. Answer the queries

    For each [l, r], return prefix[r + 1] - prefix[l].

Frequently asked questions

How do you count vowel strings in a range quickly?

Turn each word into 1 if it starts and ends with a vowel and 0 otherwise, build a prefix sum of those values, and answer a query [l, r] as prefix[r + 1] - prefix[l].


What is the time complexity of Count Vowel Strings in Ranges?

O(N + Q): one pass over the N words to build the prefix array and O(1) for each of the Q queries. Space is O(N) for the prefix array plus O(Q) for the answers.


Does a one-letter word like "e" count?

Yes. Its first and last character are the same letter, so a single vowel both starts and ends the word and it adds 1 to the prefix count.

New to the technique behind this problem? Watch it run step by step:

Prefix Sum Visualization

Applying for software engineering roles? Free, no sign-up:

AI resume checker: match your resume to the job description