Determine if String Halves Are Alike — LeetCode 1704 Python Solution
EasyStringCounting
- Problem
- #1704
- Pattern
- Hash Map
- Reading time
- 2 min
- Source
- leetcode.com
The problem
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.
Example
- Input
- s = "book"
- Output
- true
- Explanation
- a = "bo" and b = "ok". a has 1 vowel and b has 1 vowel. Therefore, they are alike.
Python solution
Python
class Solution:
def halvesAreAlike(self, s: str) -> bool:
cnt, n = 0, len(s) >> 1
vowels = set('aeiouAEIOU')
for i in range(n):
cnt += s[i] in vowels
cnt -= s[i + n] in vowels
return cnt == 0Complexity
| Measure | Complexity |
|---|---|
| Time | O(n), where n is the length of the string |
| Space | O(C), where C is the number of vowel characters auxiliary |
Pattern: Hash Map
Trade memory for time: remember what you have seen so the second pass never happens. LeetCode 1704. Determine if String Halves Are Alike is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Counting.
The hash map guide has the Python template for the pattern and the 709 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 1704. Determine if String Halves Are Alike?
- LeetCode 1704. Determine if String Halves Are Alike is rated Easy on LeetCode.
- What is the time complexity of LeetCode 1704. Determine if String Halves Are Alike?
- The Python solution on this page runs in O(n), where n is the length of the string.
- What is the space complexity of LeetCode 1704. Determine if String Halves Are Alike?
- The Python solution on this page uses O(C), where C is the number of vowel characters auxiliary space.
- What topics does LeetCode 1704. Determine if String Halves Are Alike cover?
- LeetCode 1704. Determine if String Halves Are Alike is tagged String and Counting on LeetCode.