[Leet Code] Determine if String Halves Are Alike

Matthew Boyd
2 min readFeb 5, 2021


Leetcode: https://leetcode.com/problems/determine-if-string-halves-are-alike/


You are given a string s of even length. Split this string into two halves of equal lengths, and let a be the first half and b be the second half.

Two strings are alike if they have the same number of vowels ('a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'). Notice that s contains uppercase and lowercase letters.

Return true if a and b are alike. Otherwise, return false.

Example 1:

Input: s = "book"
Output: true
Explanation: a = "bo" and b = "ok". a has 1 vowel and b has 1 vowel. Therefore, they are alike.

Example 2:

Input: s = "textbook"
Output: false
Explanation: a = "text" and b = "book". a has 1 vowel whereas b has 2. Therefore, they are not alike.
Notice that the vowel o is counted twice.

Example 3:

Input: s = "MerryChristmas"
Output: false

Example 4:

Input: s = "AbCdEfGh"
Output: true


class Solution(object):
def halvesAreAlike(self, s):
:type s: str
:rtype: bool
vowels = ["a","e", "i", "o", "u"]
first_half = 0
answer = 0
for i in range(len(s)):
if i == len(s) / 2:
first_half = answer
answer = 0
if s[i].lower() in vowels:
answer += 1
print answer
return first_half == answer


Firstly, we define a list of all the vowels in their lowercase form. Then we define two integer variables, first_half and answer.

Then we iterate over the range of the length of the string. Then we check that if we get to the half way point, we turn the value of answer to the variable first_half. In the other if statement, we turn the string element at each position (i) to lowercase and if it’s present in the vowel list, we increment the answer variable. That then means, once we get to half of the list, and first_half variable gets its assigned value from answer, and then answer is turned to value 0, the second half of the array’s vowel number will be represented by the answer variable. Then we can check first_half == answer, it will give us a true reading if they’re equal and a false value if they’re not equal.



Matthew Boyd

Learning, and posting my findings!