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.
Constraints:
2 <= s.length <= 1000s.length is even.s consists of uppercase and lowercase letters.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.
This C solution uses a helper function isVowel to check if a character is a vowel. We loop through the first half of the string and the corresponding second half to count vowels and compare their counts.
C++
Java
Python
C#
JavaScript
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.
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.
This C variant maintains a dual integer array to count the vowels from both halves of the input string. This array allows simultaneous count validation during traversal, guaranteeing optimal time use without auxiliary data structures.
C++
Java
Python
C#
JavaScript
Time Complexity: O(n) - single pass counts vowels for two halves.
Space Complexity: O(1) - constant time storage allocation.
| Approach | Complexity |
|---|---|
| Two-Pointer Vowel Count Approach | 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. |
| Character Counting via Direct Comparison | Time Complexity: O(n) - single pass counts vowels for two halves. Space Complexity: O(1) - constant time storage allocation. |
Determine if String Halves Are Alike | Live Coding with Explanation | Leetcode - 1704 • Algorithms Made Easy • 2,328 views views
Watch 9 more video solutions →Practice Determine if String Halves Are Alike with our built-in code editor and test cases.
Practice on FleetCodePractice this problem
Open in Editor