Given a string of even length, split it into two halves and determine if the two halves have the same number of vowels. Vowels are a, e, i, o, u (case-insensitive). Return true if both halves have the same vowel count, false otherwise.
For example, "book" splits into "bo" and "ok" — each has 1 vowel (o), so return true. "textbook" has "te" (1 vowel) and "xtbook" (2 vowels) — return false. An empty string returns true.
This problem teaches string slicing and character classification. It tests your ability to split a string at its midpoint and count elements matching a condition in each segment.
The solution calculates the midpoint, iterates through the first half counting vowels, then iterates through the second half counting vowels, and compares the two counts. A helper function to check if a character is a vowel keeps the code clean.
Edge cases include an empty string (return true), a two-character string with both being vowels (true), and a string with no vowels at all (both halves have 0, return true).
Example Input & Output
'a' and 'A' both have 1 vowel
'ab' has 1 vowel, 'cd' has 0 vowels
'bo' has 1 vowel, 'ok' has 1 vowel
Empty: both halves have 0 vowels
'text' has 1 vowel, 'book' has 2 vowels
Algorithm Flow
Solution Approach
Split the string at the midpoint and compare vowel counts of both halves.
Calculate the midpoint. Count vowels in the first half (0 to mid) and the second half (mid to n). Return true if the counts are equal. Use a helper to count vowels: iterate through the range and increment for each a/e/i/o/u character (case-insensitive).
Time complexity is O(n), space complexity is O(1).
Best Answers
class Solution {
public boolean solution(String s) {
String v="aeiouAEIOU";int n=s.length()/2,l=0,r=0;
for(int i=0;i<n;i++){if(v.indexOf(s.charAt(i))!=-1)l++;if(v.indexOf(s.charAt(n+i))!=-1)r++;}
return l==r;
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
