Sponsored
Sponsored
This method involves using two pointers to count the number of vowels in each half of the string.
By using a set to identify vowels, iterate through each character in both halves. Compare the final counts for equality to determine if they are alike.
Time Complexity: O(n), where n is the length of the string, as we iterate through the string once.
Space Complexity: O(1), since we use only a fixed amount of extra space.
1def halvesAreAlike(s: str) -> bool:
2 vowels = set('aeiouAEIOU')
3 n = len(s) // 2
4 count1 = sum(1 for i in range(n) if s[i] in vowels)
5 count2 = sum(1 for i in range(n, len(s)) if s[i] in vowels)
6 return count1 == count2
In this Python solution, a set is used to easily check if a character is a vowel. The string is split into two halves, and a generator expression counts the vowels in each half. If the counts are equal, the function returns true
.
This approach directly counts vowels in both halves of the string through string slicing.
Both halves of the string are iterated efficiently with a loop, accumulating vowel counts independently. The results are directly compared to ensure both halves are alike.
Time Complexity: O(n) - single pass counts vowels for two halves.
Space Complexity: O(1) - constant time storage allocation.
#include <unordered_set>
using namespace std;
bool halvesAreAlike(string s) {
unordered_set<char> vowels{'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'};
int length = s.size();
int half = length / 2;
int vowelCounts[2] = {0};
for (int i = 0; i < half; i++) {
if (vowels.count(s[i])) vowelCounts[0]++;
if (vowels.count(s[i + half])) vowelCounts[1]++;
}
return vowelCounts[0] == vowelCounts[1];
}
This C++ solution uses arrays to simultaneously gather vowel counts from both string halves. Dual storage allows localized processing, negating the need for additional refinement passes and maintains sublinear complexity.