Home
DSA Patterns
Prefix Sum
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
- Preprocessing: Create a boolean/integer array
is_validwhereis_valid[i] = 1ifwords[i]starts and ends with a vowel, else 0. - Prefix Sum: Compute prefix sum
Pofis_valid.P[i]= count of valid words inwords[0...i-1]. - Query: Answer for
[l, r]isP[r+1] - P[l].
Vowels: a, e, i, o, u
Interactive Visualization
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);56 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 }1112 const ans = [];13 for (const [l, r] of queries) {14 ans.push(prefix[r+1] - prefix[l]);15 }16 return ans;17};
