Leetcode 2586. Count the Number of Vowel Strings in Range
We need to determine how many strings in a given list are composed solely of vowels. We are given an index range [start, end] for the list, and we need to count only the strings within this specific range.
start and end indices be the same?start and end inclusive?a, e, i, o, u) for counting purposes?start and end indices are out of bounds?Let’s assume from typical cases:
a, e, i, o, u in both uppercase and lowercase.[start, end].import java.util.List;
import java.util.Set;
import java.util.HashSet;
public class VowelStringCounter {
private static final Set<Character> VOWELS = new HashSet<>();
static {
VOWELS.add('a'); VOWELS.add('e'); VOWELS.add('i'); VOWELS.add('o'); VOWELS.add('u');
VOWELS.add('A'); VOWELS.add('E'); VOWELS.add('I'); VOWELS.add('O'); VOWELS.add('U');
}
public int countVowelStringsInRange(List<String> strings, int start, int end) {
// Validate indices
if (start < 0) start = 0;
if (end >= strings.size()) end = strings.size() - 1;
if (start > end) return 0;
int count = 0;
for (int i = start; i <= end; i++) {
if (isVowelString(strings.get(i))) {
count++;
}
}
return count;
}
private boolean isVowelString(String str) {
if (str == null || str.isEmpty()) return false;
for (char c : str.toCharArray()) {
if (!VOWELS.contains(c)) {
return false;
}
}
return true;
}
public static void main(String[] args) {
VowelStringCounter counter = new VowelStringCounter();
List<String> strings = List.of("aeiou", "ACE", "OU", "a", "bcd");
System.out.println(counter.countVowelStringsInRange(strings, 0, 2)); // Output: 2
System.out.println(counter.countVowelStringsInRange(strings, 1, 4)); // Output: 1
}
}
O(1) because we iterate over a specific sub-range directly.n), we check each character within the string. Assuming the average length of each string is m, checking each character results in a time complexity of O(m).O(n)O(m)O(n * m)O(1).O(1) aside from the input storage.This approach efficiently checks and counts the vowel strings within the specified range in optimal time.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?