Problem 1704

Abstract / Summary

Check if the first and second half of a string have the same number of vowels.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 1704.py

class Solution:
    def halvesAreAlike(self, s: str) -> bool:
        have = 0
        for i, c in enumerate(s):
            if c in "aeiouAEIOU":
                have += +1 if i < len(s) // 2 else -1
        return have == 0
7 lines | 233 bytes | submitted January 13, 2024 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 79% (500k+ submissions).

Typical patterns to solve this problem:
  • Counting
  • String
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation defines a class Solution with a single method halvesAreAlike. The method receives a string s and determines whether the two halves of the string contain the same number of vowel characters. Vowels are considered case-insensitively, covering both lower-case and upper-case forms. The algorithm iterates through the characters of the input once, updating a counter that reflects the balance between vowels found in the first half and those found in the second half. At the end, the method returns True when the counter is zero, indicating an equal count of vowels in both halves, and False otherwise.

Key Steps

Initialization of the balance counter

have = 0

A single integer variable have is created to keep track of the net difference between the number of vowels encountered in the first half of the string and those encountered in the second half. Starting at zero establishes a neutral baseline before any characters are examined.

Single pass iteration with index awareness

for i, c in enumerate(s):

The loop enumerates each character c together with its index i. This dual information enables the algorithm to decide, for each vowel, whether it belongs to the left half or the right half of the string without requiring a separate slice operation. The use of enumerate ensures that the traversal is performed in a single pass, contributing to an efficient execution path.

Vowel detection and conditional counter adjustment

if c in "aeiouAEIOU":
    have += +1 if i < len(s) // 2 else -1

The conditional checks whether the current character c is a vowel by testing membership in a literal string containing all vowel characters in both cases. When a vowel is found, the counter have is incremented by +1 if the index i lies in the first half of the string (i.e., i < len(s) // 2). Otherwise, the counter is decremented by -1. This approach directly captures the net difference between the two halves: each vowel in the left half pushes the balance upward, while each vowel in the right half pulls it downward.

Final equality test

return have == 0

After processing all characters, the method evaluates whether the balance counter has returned to zero. A zero value signifies that the number of vowels added from the first half exactly matches the number subtracted from the second half, meaning the halves are alike with respect to vowel count. The boolean result of this comparison is returned as the method’s output.

Edge Cases Handled

The algorithm gracefully handles strings of even length, which is the expected input for the problem definition. When the length of s is zero, the loop body never executes, leaving have at its initial value of zero, and the method correctly returns True because both halves (both empty) contain an equal number of vowels. For strings containing only non-vowel characters, the counter never changes, and the final comparison again yields True, reflecting that both halves have zero vowels. Mixed-case inputs are accommodated by the inclusion of both lower-case and upper-case vowels in the membership test, ensuring that vowel detection is case-insensitive without additional conversion steps.

Performance Optimizations Observed

The implementation avoids creating auxiliary data structures such as sliced substrings or temporary lists. By using a single integer counter and updating it in place, memory overhead remains minimal. The decision to test membership against a literal string of vowels rather than constructing a set each iteration eliminates the cost of repeated set creation while still providing fast membership checks due to the small constant size of the literal. The conditional expression +1 if i < len(s) // 2 else -1 combines the decision and arithmetic in a single statement, reducing the number of explicit branches and keeping the inner loop body concise. The overall design leverages a single linear scan, ensuring that the work performed scales directly with the length of the input string without extraneous passes.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a long train carrying containers full of letters. This code works by looking at every letter on that train to see if it is a vowel like a, e, i, o, or u. There is a secret counter that starts at zero. When the code sees a vowel in the first half of the train, it adds one to the counter. When the code sees a vowel in the second half of the train, it takes one away from the counter. By the time the code finishes checking every single letter, it looks at the counter to see if the number has landed back on zero. If the counter is at zero, it means there are exactly the same number of vowels in the first half as there are in the second half.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 7 | μ = 7.15 | σ = 1.41

Complexity Analysis

Time: linear
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster Python Java C++ TS
WalkCCC Python Java C++
leetcode.ca Python Java C++ JS Go PHP Rust TS
Progiez Python Java C++
github black-shadows C++
chandansgowda Python
charles-wangkai Java
DimitrisJim C
everthis JS
fartem Ruby
fsq C++
halfrost Go
JoshCrozier JS
Krazune Java
lkwq007 Python
muhammadfarhankt Go
pruthvikp Python
shreymehul C#
suxrobGM C#
varunu28 Java
vthwang Java
YuriSpiridonov Python
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, JavaScript, PHP, Python, Rust, TypeScript
Progiez C++, Java, Python
black-shadows C++, C++
chandansgowda Python
charles-wangkai Java
DimitrisJim C
everthis JavaScript
fartem Ruby
fsq C++
halfrost Go
JoshCrozier JavaScript
Krazune Java
lkwq007 Python
muhammadfarhankt Go
pruthvikp Python
shreymehul C#
suxrobGM C#
varunu28 Java
vthwang Java
YuriSpiridonov Python
36 links | 22 authors | 11 languages

Videos

4 videos   did my crawler come up with invalid videos ? drop me a line.

Solved On The Same Day

5 solutions   January 13, 2024

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality