Problem
You are given a 0-indexed array of strings words
and a 2D array of integers queries
.
Each query queries[i] = [li, ri]
asks us to find the number of strings present in the range li
to ri
(both inclusive) of words
that start and end with a vowel.
Return **an array *ans
* of size queries.length
, where ans[i]
is the answer to the i
th query**.
Note that the vowel letters are 'a'
, 'e'
, 'i'
, 'o'
, and 'u'
.
Example 1:
Input: words = ["aba","bcb","ece","aa","e"], queries = [[0,2],[1,4],[1,1]]
Output: [2,3,0]
Explanation: The strings starting and ending with a vowel are "aba", "ece", "aa" and "e".
The answer to the query [0,2] is 2 (strings "aba" and "ece").
to query [1,4] is 3 (strings "ece", "aa", "e").
to query [1,1] is 0.
We return [2,3,0].
Example 2:
Input: words = ["a","e","i"], queries = [[0,2],[0,1],[2,2]]
Output: [3,2,1]
Explanation: Every string satisfies the conditions, so we return [3,2,1].
Constraints:
1 <= words.length <= 105
1 <= words[i].length <= 40
words[i]
consists only of lowercase English letters.sum(words[i].length) <= 3 * 105
1 <= queries.length <= 105
0 <= li <= ri < words.length
Solution (Java)
class Solution {
public int[] vowelStrings(String[] words, int[][] queries) {
Map<Integer,Integer> nm=new HashMap<>();
int i=0;
int b[]=new int[words.length];
for(String p:words)
{
int f=0;
char c=p.charAt(0);
char d=p.charAt(p.length()-1);
if((c=='a' || c=='e' || c=='i' || c=='o' || c=='u') && (d=='a' || d=='e' || d=='i' || d=='o' || d=='u'))
{
nm.put(i,1);
f++;
}
if(f==1)
{
b[i]=1;
}
if(i>0)
{
b[i]+=b[i-1];
}
i++;
}
int m=0;
int a[]=new int[queries.length];
for(int p[]: queries)
{
int c=0;
if(p[1]==0)
{
if(nm.containsKey(p[1]))
{
c++;
}
a[m++]=c;
}
else if(p[0]==0)
{
a[m++]=b[p[1]];
}
else
{
a[m++]=b[p[1]]-(b[p[0]-1]);
}
}
return a;
}
}
Explain:
nope.
Complexity:
- Time complexity : O(n).
- Space complexity : O(n).