Code Logo

String Halves Alike

Published at25 Jul 2026
Medium 0 views
Like0

Given a string s of even length, split it into two halves of equal length. Return true if both halves have the same number of vowels (a, e, i, o, u, case-insensitive). If the string length is odd, it cannot have equal halves — but for this problem, the input will always have even length.

Count vowels in the first half and in the second half. Compare the counts. Vowels are 'a', 'e', 'i', 'o', 'u' and their uppercase equivalents. Use a vowels set for quick lookup.

Time complexity is O(n) and space is O(1). Only half-length iterations and a vowel lookup set are needed.

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
Recommendation Algorithm Flow for String Halves Alike

Solution Approach

function solution(s) {
  var v = 'aeiouAEIOU';
  var mid = s.length / 2;
  var left = 0, right = 0;
  for (var i = 0; i < mid; i++) {
    if (v.indexOf(s.charAt(i)) !== -1) left++;
    if (v.indexOf(s.charAt(mid + i)) !== -1) right++;
  }
  return left === right;
}

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