Category: Easy | Concepts used: String iteration, nested loops, frequency counting, null-safety
Problem Statement
Part A: Given a string, count how many vowels (a, e, i, o, u, case-insensitive) it contains.
Part B: Given an array of strings, count the total number of vowels across all of them.
Input : "Education" Output: 5 (E, u, a, i, o)
Input : ["Hi", "Bye"] Output: 2 (i from "Hi", e from "Bye")
Examples (with edge scenarios)
| # | Input | Output | Why |
|---|---|---|---|
| 1 | "Education" | 5 | E, u, a, i, o |
| 2 | "" (empty) | 0 | Contains no characters |
| 3 | "xyz" | 0 | No vowels present |
| 4 | ["Hi", "", "Bye"] | 2 | "Hi" โ 1 (i), "" โ 0, "Bye" โ 1 (e) |
| 5 | ["AEIOU"] | 5 | All 5 vowels in one string |
โ ๏ธ Common Beginner Mistake
Mistake Impact Fix Re-initializing the accumulator inside the loop Resets totals, losing counts from previous strings Declare totalCountoutside the array loopIgnoring nullelements in the arrayThrows NullPointerExceptionInclude a null-check if (word != null)before processing
Before You Code: Clarify the Contract
Before choosing an algorithm, confirm how null and empty strings should behave, whether comparison is case-sensitive, and whether spaces or punctuation count. Java char values are UTF-16 code units, not always complete human-visible Unicode characters, so international text may require code points or grapheme-aware libraries.
Analogy: Counting Gold Coins in Treasure Chests
Imagine you are a pirate treasure counter inspecting a collection of treasure chests:
- Single Chest (Single String): You open one chest containing mixed items (characters). You inspect them one by one. Every time you find a gold coin (vowel), you add 1 to your tally. You must look through the entire chest to ensure you donโt miss any coins.
- Multiple Chests (Array of Strings): You have a row of chests. You count the gold coins in the first chest, write down the result, move to the next chest, count its coins, and add them to your running total. If a chest is empty (empty string) or missing (
null), you simply move to the next one.
Solution 1 โ Count Vowels in a Single String
This approach counts vowels in a single string by checking each index position.
Intuition
Unlike checking for presence (where we exit early), counting requires us to scan the entire string. We maintain a running tally (count) and increment it every time the character is found in our vowel lookup set.
public class CountVowels {
public static int countVowels(String str) {
if (str == null || str.isEmpty()) {
return 0;
}
String vowels = "aeiouAEIOU";
int count = 0;
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
if (vowels.indexOf(ch) != -1) { // Found in the vowel list
count++;
}
}
return count;
}
public static void main(String[] args) {
System.out.println(countVowels("Education")); // 5
System.out.println(countVowels("")); // 0
System.out.println(countVowels("xyz")); // 0
}
}
Output:
5
0
0
Dry Run (str = โByeโ)
vowels = "aeiouAEIOU"
i = 0: 'B' -> index of 'B' = -1 (not found)
i = 1: 'y' -> index of 'y' = -1 (not found)
i = 2: 'e' -> index of 'e' = 1 (found!) -> count = 1
Final count = 1
Solution 2 โ Count Total Vowels Across an Array of Strings
This solution loops through the array, using the single-string method as a helper function.
Intuition
Calculating the total vowels across an array is equivalent to finding the sum of vowels in each individual string. Reusing the helper function avoids deep nesting and makes the code clean and testable.
public class CountVowelsInArray {
public static int countVowels(String str) {
if (str == null || str.isEmpty()) {
return 0;
}
String vowels = "aeiouAEIOU";
int count = 0;
for (int i = 0; i < str.length(); i++) {
if (vowels.indexOf(str.charAt(i)) != -1) {
count++;
}
}
return count;
}
public static int countVowelsInArray(String[] words) {
if (words == null) {
return 0;
}
int totalCount = 0;
for (String word : words) {
if (word != null) { // Safe guard against null elements
totalCount += countVowels(word);
}
}
return totalCount;
}
public static void main(String[] args) {
String[] words = {"Hi", "", "Bye"};
System.out.println(countVowelsInArray(words)); // 2
String[] words2 = {"AEIOU"};
System.out.println(countVowelsInArray(words2)); // 5
}
}
Output:
2
5
๐ Visual Flowchart
graph TD
Start["Input Array of Strings"] --> InitTotal["Initialize totalCount = 0"]
InitTotal --> LoopArray{"More words in array?"}
LoopArray -->|Yes| CheckNull{"word == null?"}
CheckNull -->|Yes| LoopArray
CheckNull -->|No| InitWordCount["Initialize wordCount = 0"]
InitWordCount --> LoopChar{"More chars in word?"}
LoopChar -->|Yes| CheckVowel{"Is char in 'aeiouAEIOU'?"}
CheckVowel -->|Yes| IncWord["Increment wordCount"]
CheckVowel -->|No| LoopChar
IncWord --> LoopChar
LoopChar -->|No| AddTotal["totalCount += wordCount"]
AddTotal --> LoopArray
LoopArray -->|No| End["Return totalCount"]
Interviewer Insights
This question tests modular code design and edge case handling.
Follow-up questions you might get:
- โWhat if the array has millions of characters? Can we run it in parallel?โ โ Yes. In Java, you can use streams:
Arrays.stream(words) .parallel() .filter(Objects::nonNull) .mapToInt(CountVowels::countVowels) .sum(); - โWhat if the string contains accented vowels like โรฉโ or โรผโ?โ โ Standard ASCII range checks will miss these. For internationalized applications, use Unicode properties (like normalizing characters using
java.text.Normalizerto strip accents before running the check).
Quick Recap
| Version | Approach | Time Complexity | Space Complexity | Interview Signal |
|---|---|---|---|---|
| Single string | Single-loop search | (O(N)) | (O(1)) | Standard string manipulation |
| Array of strings | Loop + helper function | (O(\sum \text{len}(\text{words}))) | (O(1)) | Demonstrates modular code reuse and null safety |
- Author
- TechByteByByte Editorial Team
- Reviewed by
- TechByteByByte Admin
- Published
- Last reviewed