Problem 1704
Question statement:
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.
Solution:
Main idea:
To deal with the case sensitivity, we first turn the string to all lower case symbols.
Brute force approach: We split the string into two halves. Initialize two counters to 0. Traverse through the two substrings, updating the counter everytime a vowel is encountered. Finally return counter1==counter2.
Brute force but cheeky approach: We can do the above in a single pass via a two pointer approach. Initialize the first pointer to index 0, and the second pointer to the midpoint (mid) of the string. As the index ranges from 0 to mid, update counter by +1 if a vowel is encountered at s[i] and update it by -1 if a vowel is encountered at s[mid+i]. Finally, return counter == 0.
Code:
Brute force:
1 | def halvesAreAlike(self, s: str) -> bool: |
Brute force but cheeky:
1 | def halvesAreAlike(self, s: str) -> bool: |
Comments:
Time complexity for both approaches: O(n)
At the time of submission, the first solution passes leetcode submission cases in 36ms, beats 87.10% of users. It uses 17.46MB of memory, beating 9.07% of users.
At the time of submission, the second solution passes leetcode submission cases in 35ms, beats 90.17% of users. It uses 17.20MB of memory, beating 33.46% of users.