Code Logo

String Halves Alike

Published at25 Jul 2026
Medium 0 views
Like0

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

Example 1
Input
"aA"
Output
true
Explanation

'a' and 'A' both have 1 vowel

Example 2
Input
"abcd"
Output
false
Explanation

'ab' has 1 vowel, 'cd' has 0 vowels

Example 3
Input
"book"
Output
true
Explanation

'bo' has 1 vowel, 'ok' has 1 vowel

Example 4
Input
""
Output
true
Explanation

Empty: both halves have 0 vowels

Example 5
Input
"textbook"
Output
false
Explanation

'text' has 1 vowel, 'book' has 2 vowels

Algorithm Flow

Recommendation Algorithm Flow for String Halves Alike

Solution Approach

Split the string at the midpoint and compare vowel counts of both halves.

function halvesAreAlike(s)
  n = length(s), mid = n / 2
  count1 = countVowels(s, 0, mid)
  count2 = countVowels(s, mid, n)
  return count1 == count2

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

java
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;
    }
}