#1704

Determine if String Halves Are Alike

Easy
StringCountingHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

The optimal solution uses a single pass to count the vowels in both halves simultaneously, which reduces the number of iterations needed.

⚙️

Algorithm

5 steps
  1. 1Step 1: Initialize a vowel count variable.
  2. 2Step 2: Loop through the first half and the second half of the string simultaneously.
  3. 3Step 3: For each character, check if it's a vowel and update the count accordingly.
  4. 4Step 4: After the loop, check if the counts are equal.
  5. 5Step 5: Return true if they are equal, otherwise return false.
solution.py12 lines
1# Full working Python code
2
3def halvesAreAlike(s):
4    n = len(s)
5    count = 0
6    vowels = 'aeiouAEIOU'
7    for i in range(n // 2):
8        if s[i] in vowels:
9            count += 1
10        if s[n - 1 - i] in vowels:
11            count -= 1
12    return count == 0

Complexity note: The time complexity remains O(n) as we still iterate through half of the string, but we only use a single variable for counting, making the space complexity O(1).

  • 1Both halves must have the same number of vowels.
  • 2Using a single pass can significantly optimize the solution.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.