Determine if String Halves Are Alike

Updated on 22 May, 2025
Determine if String Halves Are Alike header image

Problem Statement

Imagine you are given a string, s, which always has an even length. Your task involves processing this string to determine if two substrings of s are "alike." Here's how you would go about it:

  1. First, divide the string, s, into two equal halves; the first half is labelled as a, and the second half is labelled as b.
  2. The two substrings, a and b, are considered alike if both contain the same number of vowels. The vowels in question are a, e, i, o, and u, as well as their uppercase counterparts.
  3. Vowels should be counted regardless of their case, meaning both 'A' and 'a' count as the same vowel.
  4. Depending on whether a and b have an equal number of vowels, you will then return true if they do, and false if they don't.

This problem requires you primarily to analyze and manipulate strings, also dealing with fundamental operations like substring extraction and character counting.

Examples

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.

Constraints

  • 2 <= s.length <= 1000
  • s.length is even.
  • s consists of uppercase and lowercase letters.

Approach and Intuition

Let's delve into how one might solve this problem, using the given examples to illustrate:

  • Example 1: For the string s = "book", the substrings are a = "bo" and b = "ok". Counting the vowels:

    • a has 1 vowel (o).
    • b also has 1 vowel (o).
    • Since both substrings have the same number of vowels, they are alike. Thus, the function would return true.
  • Example 2: For the string s = "textbook", the substrings are a = "text" and b = "book".

    • a contains 1 vowel (e).
    • b contains 2 vowels (o, and o counted twice).
    • The counts differ, so a and b are not alike, meaning the function would return false.

Approach:

  • First, define what counts as a vowel using a set or list for quick checking.
  • Split the string exactly in the middle.
  • Iterate through each half, counting the occurrence of vowels.
  • Compare the counts.
  • Return true if the counts match (alike), or false if they do not match.

This method relies primarily on linear traversal of the string halves and basic counting operations, making it straightforward yet efficient given the problem constraints.

Solutions

  • C++
  • Java
  • Python
cpp
class Solution {
public:
    bool halvesAreAlike(string str) {
        int len = str.length();
        return vowelCount(0, len / 2, str) == vowelCount(len / 2, len, str);
    }

    int vowelCount(int start, int end, string& str) {
        string vowelSet = "aeiouAEIOU";
        int count = 0;
        for (int index = start; index < end; index++) {
            if (vowelSet.find(str[index]) != string::npos) {
                count++;
            }
        }
        return count;
    }
};

This solution in C++ checks whether the two halves of a given string are "alike", meaning they have the same number of vowels. The process involves the following steps:

  1. Determine the length of the string and divide it into two equal parts.
  2. Compare the number of vowels in the first half with the number of vowels in the second half using a helper function vowelCount.

The vowelCount function works as follows:

  • It accepts starting and ending indices of the string segment and a reference to the string.
  • Initialize a count of vowels to zero.
  • Loop through the specified range of the string.
  • For each character in the specified range, check whether it is a vowel (both lower and uppercase are considered) using a predefined string vowelSet.
  • If a vowel is found, increment the count.
  • Return the total count of vowels found in the specified string segment.

Finally, the halvesAreAlike function compares the vowel counts of the two halves. If they are the same, it returns true, otherwise false. This provides a simple and efficient method to determine if the two halves of the string contain an equal number of vowels.

java
class Solution {
    public boolean halvesAreAlike(String str) {
        int length = str.length();
        return getVowelCount(0, length / 2, str) == getVowelCount(length / 2, length, str);
    }

    private int getVowelCount(int startIdx, int endIdx, String str) {
        String vowels = "aeiouAEIOU";
        int vowelCount = 0;
        for (int idx = startIdx; idx < endIdx; idx++) {
            if (vowels.indexOf(str.charAt(idx)) >= 0) {
                vowelCount++;
            }
        }
        return vowelCount;
    }
}

This Java solution to the problem of determining if the two halves of a given string contain an equal number of vowels effectively splits the string into two halves and compares the vowel counts of each half. Here's how the solution works:

  • Utilizes a main method called halvesAreAlike, which takes a string and first determines its length. It then divides this string into two halves, using the length to index the string properly.
  • Calls a helper method, getVowelCount, for each string half. getVowelCount calculates the number of vowels in each substring from the start index to the end index.
  • The list of vowels includes both uppercase and lowercase vowels for comprehensiveness.
  • The main halvesAreAlike method compares the number of vowels in both halves using a simple equality check, returning true if they are equal and false otherwise.

This method offers a clear and efficient approach to comparing parts of a string based on specified character features — in this case, vowels. The solution is both easy to understand and apply for strings of any permissible length.

python
class Solution:
    def checkHalvesVowelEquality(self, string: str) -> bool:

        def vowelCount(first, last, inputStr):
            vowelSum = 0
            for idx in range(first, last):
                if inputStr[idx] in "aeiouAEIOU":
                    vowelSum += 1
            return vowelSum

        length = len(string)

        return vowelCount(0, length//2, string) == vowelCount(length//2, length, string)

The given Python solution defines a method to determine if two halves of a string have the same number of vowels. The solution is encapsulated within a class Solution and consists of an internal helper function named vowelCount.

Here's an outline of the solution:

  • vowelCount(first, last, inputStr): This helper function calculates the number of vowels in the substring of inputStr starting from index first to last (non-inclusive). It iterates over each character in the specified range, checks if it is a vowel (either uppercase or lowercase), and counts it.

  • The main function checkHalvesVowelEquality calculates the length of the input string and splits it into two halves. It compares the count of vowels in the first half of the string (from the beginning to the midpoint) with the count of vowels in the second half (from the midpoint to the end). If both halves have the same number of vowels, it returns True; otherwise, it returns False.

Ensure to pass a string to checkHalvesVowelEquality when calling this method. The function handles strings of both even and odd lengths correctly by utilizing integer division (length//2) to determine the midpoint.

Comments

No comments yet.