Determine if String Halves Are Alike (LeetCode 1704): Solution and Explanation

Easy
String
Counting

Cut an even-length string in the middle and return whether both halves contain the same number of vowels, counting uppercase vowels too.

Intuition

The question only cares about one number per half: how many vowels it holds. Everything else about the letters is irrelevant.

Think of the two halves as the pans of a scale where every vowel weighs one unit and every consonant weighs nothing. The halves are alike exactly when the scale balances.

Since both halves have the same length, index i of the first half lines up with index i + half of the second. One loop over i can drop a weight on each pan at the same time.

Approach: Count vowels in both halves in one pass

  1. Compute half = len(s) / 2.
  2. Set left = right = 0.
  3. For each i in [0, half), add 1 to left if s[i] is a vowel and add 1 to right if s[i + half] is a vowel. Check both cases.
  4. Return left == right.

Step-by-step example

s = "textbook"
  1. half = 4, so a = "text" and b = "book".
  2. Pair 0: t and b, no vowels. 0 vs 0.
  3. Pair 1: e and o, both vowels. 1 vs 1.
  4. Pair 2: x and o, only o. 1 vs 2.
  5. Pair 3: t and k, no vowels. 1 vs 2.
  6. 1 is not 2, so return false.

Code: Python, Java, C++

1class Solution:
2    def halvesAreAlike(self, s: str) -> bool:
3        vowels = set('aeiouAEIOU')
4        half = len(s) // 2
5        left = 0
6        right = 0
7        for i in range(half):
8            if s[i] in vowels:
9                left += 1
10            if s[i + half] in vowels:
11                right += 1
12        return left == right
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n)

Each character is checked once against a fixed set of ten vowels.

Space

O(1)

Two counters and a constant vowel set.

Other approaches

Single balance counter (time O(n), space O(1))

Keep one counter: add 1 for a vowel in the first half and subtract 1 for a vowel in the second. Return whether it ends at zero.

Count each half separately (time O(n), space O(n))

Slice the string into two halves and count vowels in each with a helper or a built-in. Clear, at the cost of copying the halves.

Common mistakes

  • Forgetting uppercase vowels. 'A', 'E', 'I', 'O' and 'U' count too.
  • Treating 'y' as a vowel. It is not in this problem's vowel set.
  • Comparing the halves as strings or as letter multisets instead of only comparing vowel counts.

Frequently asked questions

Do the vowels have to be the same letters?

No. Only the counts matter: "ab" + "eb" is alike even though the vowels differ.

Can the string length be odd?

No, the constraints guarantee an even length, so the two halves are always the same size.