#3227

Vowels Game in a String

Medium
MathStringBrainteaserGame TheoryGame TheoryCountingString Manipulation
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 leverages the count of vowels in the entire string. If Alice starts with an odd number of vowels, she can remove the entire string and win immediately. If there are no vowels, she cannot make a move and loses.

⚙️

Algorithm

4 steps
  1. 1Step 1: Count the total number of vowels in the string.
  2. 2Step 2: If the count is 0, return false (Alice loses).
  3. 3Step 3: If the count is odd, return true (Alice wins).
  4. 4Step 4: If the count is even, return false (Alice loses).
solution.py3 lines
1def canAliceWin(s):
2    vowels = sum(1 for c in s if c in 'aeiou')
3    return vowels > 0 and vowels % 2 == 1

Complexity note: The time complexity is O(n) because we only need to traverse the string once to count vowels. The space complexity is O(1) since we are using a fixed amount of space regardless of input size.

  • 1Alice can win immediately if the total number of vowels is odd.
  • 2If there are no vowels, Alice cannot make a move and loses.

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