Category: Easy | Concepts used: String iteration, character checks, character sets
Problem Statement
Given a string, check whether it contains at least one vowel (a, e, i, o, u โ uppercase or lowercase).
Input : "Hello" Input : "sky" Input : "PQRST"
Output: true Output: false Output: false
Examples (with edge scenarios)
| # | Input | Output | Why |
|---|---|---|---|
| 1 | "Hello" | true | Contains e, o |
| 2 | "sky" | false | y is not treated as a vowel |
| 3 | "" (empty string) | false | Contains no characters |
| 4 | "AEIOU" | true | Case-insensitive match |
| 5 | "123 xyz!" | false | Only contains digits, spaces, symbols, and consonants |
โ ๏ธ Common Beginner Mistake
Mistake Impact Fix Checking only lowercase vowels Misses uppercase inputs like "HELLO"Convert the character or string to lowercase before checking Forgetting the empty string case Throws out-of-bounds error on custom indexing Ensure the loop range is correctly set to < length()and the default return isfalse
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: Sorting Mail at a Post Office
Imagine you are a postal worker checking a box of incoming letters:
- You have a strict rule: โIf there is even one letter in this box addressed to the VIP suite (Vowels), flag the whole box immediately.โ
- You pull the letters out one by one. The moment you see a letter addressed to
A,E,I,O, orU, you stop digging, raise the flag (return true), and move on. - If you check the entire box and never see a VIP address, you put the box down without a flag (
return false).
Solution 1 โ Loop + if-else Chain (Most Basic)
This is the standard iterative approach checking every character sequentially.
Intuition
To find if a string contains a vowel, we inspect each character one by one. Returning true as soon as a vowel is found (early exit / short-circuiting) saves unnecessary CPU cycles.
public class VowelCheck {
public static boolean hasVowel(String str) {
if (str == null || str.isEmpty()) {
return false;
}
// Convert to lowercase once to handle case-insensitivity
String lower = str.toLowerCase();
for (int i = 0; i < lower.length(); i++) {
char ch = lower.charAt(i);
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
return true; // Found one vowel, stop immediately
}
}
return false; // Loop finished without finding any vowel
}
public static void main(String[] args) {
System.out.println(hasVowel("Hello")); // true
System.out.println(hasVowel("sky")); // false
System.out.println(hasVowel("")); // false
System.out.println(hasVowel("AEIOU")); // true
}
}
Output:
true
false
false
true
Dry Run (str = โskyโ)
lower = "sky"
i = 0: ch = 's' -> not a vowel
i = 1: ch = 'k' -> not a vowel
i = 2: ch = 'y' -> not a vowel
Loop ends -> return false
Solution 2 โ Lookup Set via String.contains() (Concise)
Using a constant string reference containing all vowels simplifies syntax.
Intuition
Instead of chaining || operators, we define a reference string of vowels ("aeiouAEIOU") and verify whether each character of the input exists inside it using String.indexOf() or String.contains().
public class VowelCheckContains {
public static boolean hasVowel(String str) {
if (str == null || str.isEmpty()) {
return false;
}
String vowels = "aeiouAEIOU";
for (char ch : str.toCharArray()) {
// String.indexOf(ch) >= 0 is more efficient than string conversion for contains()
if (vowels.indexOf(ch) != -1) {
return true;
}
}
return false;
}
public static void main(String[] args) {
System.out.println(hasVowel("Hello")); // true
System.out.println(hasVowel("sky")); // false
}
}
Output:
true
false
๐ Visual Flowchart
graph TD
Start["Input String S"] --> Empty{"S is empty/null?"}
Empty -->|Yes| RetFalse["Return False"]
Empty -->|No| Iterate["Iterate through chars"]
Iterate --> Loop{"More characters?"}
Loop -->|Yes| Inspect{"Is char in 'aeiouAEIOU'?"}
Inspect -->|Yes| Found["Return True"]
Inspect -->|No| Loop
Loop -->|No| NotFound["Return False"]
Interviewer Insights
This question is a filter for basic logical flow control and edge case analysis.
Follow-up questions you might get:
- โHow can you solve this using Regular Expressions?โ โ Mention
str.matches(".*[aeiouAEIOU].*"). While regex is concise, regular loops are generally faster because compiling and matching regex objects carries computational overhead. - โWhat is the time complexity if the string is very long?โ โ It is (O(N)) where (N) is the length of the string, since in the worst-case scenario (no vowels), we must inspect every character exactly once.
Quick Recap
| Approach | Time Complexity | Space Complexity | Handles Negatives/Symbols? | Interview Signal |
|---|---|---|---|---|
| Loop + if-else | (O(N)) | (O(1)) | Yes | Simple, robust, clear logical boundaries |
| Lookup String | (O(N)) | (O(1)) | Yes | Clean lookup representation, avoids complex ` |
- Author
- TechByteByByte Editorial Team
- Reviewed by
- TechByteByByte Admin
- Published
- Last reviewed