Vowels Game in a String Problem
#3227
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 3227.
Alice and Bob are playing a game on a string.
You are given a string s, 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
sthat contains an odd number of vowels. - On Bob's turn, he has to remove any non-empty substring from
sthat 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.
Example 1:
Input: s = "leetcoder"
Output: true
Explanation:
Alice can win the game as follows:
- Alice plays first, she can delete the underlined substring in s = "leetcoder" which contains 3 vowels. The resulting string is s = "der".
- Bob plays second, he can delete the underlined substring in s = "der" which contains 0 vowels. The resulting string is s = "er".
- Alice plays third, she can delete the whole string s = "er" which contains 1 vowel.
- Bob plays fourth, since the string is empty, there is no valid play for Bob. So Alice wins the game.
Example 2:
Input: s = "bbcd"
Output: false
Explanation:
There is no valid play for Alice in her first turn, so Alice loses the game.
Constraints:
1 <= s.length <= 10^5sconsists only of lowercase English letters.
Solution
Approach: Case Analysis
Let k be the number of vowels in s.
- If
k = 0, Alice has no valid move and loses. - If
kis odd, Alice can remove the whole string and wins. - If
kis even, Alice removes a substring withk - 1vowels, leaving an odd number (one) of vowels. Bob must remove a substring with an even number of vowels, so an odd number of vowels always remains for Alice, who then removes the whole string and wins.
So Alice wins exactly when s contains at least one vowel.
Complexity: time O(n), space O(1).
class Solution:
def doesAliceWin(self, s: str) -> bool:
vowels = set("aeiou")
return any(c in vowels for c in s)