Vowels Game in a String - Problem

Alice and Bob are playing a game on a string. You are given a string s, and Alice and Bob will take turns playing the following game where Alice starts first:

  • On Alice's turn, she has to remove any non-empty substring from s that contains an odd number of vowels.
  • On Bob's turn, he has to remove any non-empty substring from s that contains an even number of vowels.

The first player who cannot make a move on their turn loses the game. We assume that both Alice and Bob play optimally.

Return true if Alice wins the game, and false otherwise.

The English vowels are: a, e, i, o, and u.

Input & Output

Example 1 — String with vowels
$ Input: s = "leetcodeisgreat"
Output: true
💡 Note: Alice can remove any single vowel (like 'e') which has odd count 1, forcing the game to continue until she wins
Example 2 — String with no vowels
$ Input: s = "bbcd"
Output: false
💡 Note: No vowels in string, so Alice cannot make any move and loses immediately
Example 3 — Single vowel
$ Input: s = "a"
Output: true
💡 Note: Alice takes the single vowel 'a' (odd count = 1), Bob has no moves left, Alice wins

Constraints

  • 1 ≤ s.length ≤ 105
  • s consists only of lowercase English letters

Visualization

Tap to expand
Vowels Game in a String INPUT String s: l e e t c o d e i s g r e a t Vowel (a,e,i,o,u) Consonant Total Vowels Count: 7 (odd number) Game Rules: Alice: Remove substring with ODD vowels Bob: Remove substring with EVEN vowels First unable to move loses! ALGORITHM STEPS 1 Count Vowels Count total vowels in string vowels = 7 2 Check if vowels > 0 If at least 1 vowel exists, Alice can always play 3 Alice's Strategy Remove entire string (odd vowels) or single vowel 4 Return Result If vowels >= 1: Alice wins If vowels == 0: Bob wins Optimal Logic: if (vowelCount >= 1) return true; // Alice else return false; // Bob FINAL RESULT ALICE WINS! Output: true Why Alice Wins: String has 7 vowels (odd) Alice removes entire string String becomes empty Bob cannot move Alice wins in 1 move! Key Insight: If there's at least ONE vowel, Alice ALWAYS wins! She can remove a substring with exactly 1 vowel (which is odd). This forces Bob into a losing position. The problem reduces to: return (vowelCount >= 1) Time: O(n) | Space: O(1) - Just count vowels! TutorialsPoint - Vowels Game in a String | Optimal Solution
Asked in
Google 25 Meta 20
12.0K Views
Medium Frequency
~15 min Avg. Time
450 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen